[英]Violation of PRIMARY KEY constraint with Entity Framework 6 , Model one-to-many
I have 2 models with one to many relation, if I save in different instance of DbContext
, this throw an exception (Violation of Primary Key) - how to avoid it? 我有2个具有一对多关系的模型,如果我保存在
DbContext
不同实例中, DbContext
抛出异常(违反主键)-如何避免呢?
public class Customer
{
public Guid Id { get; set; }
public string Name { get; set; }
}
public class User
{
public Guid Id { get; set; }
public string Name { get; set; }
public Customer Customer { get; set; }
}
public class DbContext : System.Data.Entity.DbContext
{
public DbContext()
: base(@"Data Source=(localdb)\MSSQLLocalDB; AttachDBFilename='|DataDirectory|\Sample.mdf'; Integrated Security=True")
{
Configuration.ProxyCreationEnabled = false;
Configuration.AutoDetectChangesEnabled = true;
Configuration.ValidateOnSaveEnabled = true;
Configuration.LazyLoadingEnabled = true;
}
public IDbSet<Customer> Customers { get; set; }
public IDbSet<User> Users { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Properties<Guid>()
.Where(p => p.Name == "Id")
.Configure(p => { p.IsKey(); p.IsRequired(); });
}
}
AppDomain.CurrentDomain.SetData(
"DataDirectory",
System.Environment.CurrentDirectory);
var customer = new Customer();
customer.Id = Guid.NewGuid();
customer.Name = "customername";
using (var db = new DbContext())
{
db.Customers.Add(customer);
db.SaveChanges();
}
var user = new User();
user.Id = Guid.NewGuid();
user.Name = "username";
user.Customer = customer;
using (var db = new DbContext())
{
db.Users.Add(user);
db.SaveChanges(); // <- Throw here
}
of course this is a simplified sample, in what is written it is possible to use only one instance of DbContext
, but in reality the customer is passed as a parameter to a method 当然,这是一个简化的示例,在编写过程中,仅可以使用一个
DbContext
实例,但实际上,将客户作为参数传递给方法
You are correct - the second instance won't know you just added the customer. 您是正确的-第二个实例不会知道您刚刚添加了客户。 Either wrap them in the same using statement or you can tell the second instance the customer already exists:
可以将它们包装在相同的using语句中,或者可以告诉第二个实例该客户已经存在:
var user = new User();
user.Id = Guid.NewGuid();
user.Name = "username";
using (var db = new DbContext())
{
user.Customer = new Customer() { Id = customer.Id }; // only need the id
db.Customers.Attach(user.Customer);
db.Users.Add(user);
db.SaveChanges();
}
Entity Framework: adding existing child POCO to new Parent POCO, creates new child in DB 实体框架:将现有的子POCO添加到新的父POCO,在数据库中创建新的子POCO
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.