While I understand there are many articles online about this I cannot seem to find solution to my problem. One reason is all articles I found aren't using async function. Here is my problem:
I have entity:
[Key]
public int Id { get; set; }
[Required]
public string Name { get; set; }
[Url]
public string LogoUrl { get; set; }
[Required]
public string AdministratorIdentityId { get; set; }
public string Verified { get; set; }
public int AddressId { get; set; }
I have following in my db context:
protected override void OnModelCreating(ModelBuilder model)
{
model.Entity<RestaurantEntity>()
.Property(p => p.Id)
.ValueGeneratedNever();
base.OnModelCreating(model);
}
And my code to save information to database is this:
try
{
RestaurantEntity dbrestaurant = new RestaurantEntity();
dbrestaurant.Name = restaurantName;
dbrestaurant.AdministratorIdentityId = restaurantAdministrator;
dbrestaurant.Verified = GenerateVerifiedCode();
await _appDbContext.Restaurants.AddAsync(dbrestaurant);
await _appDbContext.SaveChangesAsync();
int newpk = dbrestaurant.Id;
return newpk;
}
My problem is that newpk is ALWAYS 0, while in DB generates proper value. For some reason EF core is not retrieving inserted value.
This is code retrieving info:
This is DB value:
Change,
[Key]
public int Id { get; set; }
to
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id {get;set;}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.