I have two entities where entity A has a foreign key to entity B. Entity PK's are autogenerated in DB. When I create a new object for each of those entities and links entity A to B, I expect SaveChanges() to update foreign key in entity A after saving entity B and before saving entity A, but this doesn't happen - am I expecting too much? Do I have to use two SaveChanges()-calls?
Code:
public class Product
{
[Key]
public int ProductId { get; set; }
[Required]
public int ProductTypeId { get; set; }
[ForeignKey("ProductTypeId")]
public virtual ProductType ProductTypeRef { get; set; }
}
public class ProductType
{
[Key]
public int ProductTypeId { get; set; }
}
Product product = new Product();
product.ProductTypeRef = new ProductType();
_context.Products.Add(product);
_context.SaveChanges(); // leads to exception telling foreign key constraint not met
This works fine for me:
using System;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity;
using System.Data;
using System.Diagnostics;
using System.Threading.Tasks;
namespace Ef6Test
{
public class Product
{
[Key]
public int ProductId { get; set; }
[Required]
public int ProductTypeId { get; set; }
[ForeignKey("ProductTypeId")]
public virtual ProductType ProductType { get; set; }
}
public class ProductType
{
[Key]
public int ProductTypeId { get; set; }
}
class Db : DbContext
{
public DbSet<Product> Products { get; set; }
public DbSet<ProductType> ProductTypes { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
}
}
class Program
{
static void Main(string[] args)
{
Database.SetInitializer(new DropCreateDatabaseAlways<Db>());
using (var db = new Db())
{
Product product = new Product();
product.ProductType = new ProductType();
db.Products.Add(product);
db.SaveChanges(); // works fine
}
Console.WriteLine("Hit any key to exit");
Console.ReadKey();
}
}
}
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.