[英]Entity framework: When adding to new entities, how to use autogen ID from entity B as foreign key in entity A?
I have two entities where entity A has a foreign key to entity B. Entity PK's are autogenerated in DB. 我有两个实体,其中实体A具有到实体B的外键。实体PK在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? 当我为每个实体创建一个新对象并将实体A链接到B时,我希望SaveChanges()在保存实体B之后并在保存实体A之前更新实体A中的外键,但这不会发生-我期望太多了? Do I have to use two SaveChanges()-calls? 我必须使用两次SaveChanges()调用吗?
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();
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.