In reference to the selected answer in How can I get Id of inserted entity in Entity Framework? work for an Identity field that is a Guid?
Also, is there a way to just do a simple `SELECT @@IDENTITY' in a repository and interface setting?
Edit 1
I need to be able insert a record using the generic Repo method.
My model:
[Table(name: "Images")]
public class ImagesViewModel
{
[Key, Required, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid RecordID { get; set; }
[Column(TypeName = "image")]
public byte[] MainImage { get; set; }
public string MainImageMimeType { get; set; }
[Column(TypeName = "image")]
public byte[] ImageThumbnail { get; set; }
public string ImageThumbnailMimeType { get; set; }
public bool Enabled { get; set; }
public bool PrimaryImage { get; set; }
public bool RelatedImage { get; set; }
public Guid? RelatedImageID { get; set; }
public ImagesViewModel()
{
Enabled = true;
PrimaryImage = true;
RelatedImage = false;
}
}
If I was doing a stored procedure, I could simply do a SELECT @@IDENTITY
and return the value of the identity field or the newly inserted record.
Unfortunately, I am using code-first with a generic data repository. So far I have the following method (work in progress):
public virtual Guid Add<T>(T newItem) where T : class
{
using (var context = new ApplicationDbContext())
{
context.Set<T>().Add(newItem);
context.SaveChanges();
context.Entry(newItem).
return _ImagesViewModel.RecordID;
};
}
So I guess I am asking, what is the proper way of doing this?
Edit 2
Here is an updated code snippet of the Add method (work in progress):
public virtual Guid Add<T>(T entity) where T : BaseEntity
{
using (var context = new ApplicationDbContext())
{
DbSet dbSet = context.Set<T>();
dbSet.Add(entity);
context.SaveChanges();
return entity.RecordID;
}
}
public abstract class BaseEntity
{
Guid RecordID { get; set; }
}