简体   繁体   English

为什么在使用DbSet.Add()时无法添加新创建的主体实体?

[英]Why I can't add newly created principal entity when use DbSet.Add()?

I have two classes and they are in one to one relationship 我有两节课,他们是一对一的关系

public class Car
{
    public long Id { get; set; }
    public string Name { get; set; }
    public long CompanyId { get; set; }
    public Company Company { get; set; }
}

public class Company
{
    public long Id { get; set; }
    public string Name { get; set; }
    public Car Car { get; set; }
}

and let's say I have added one record (with id = 1) to the Company table, so now I want to add a new Car record as 假设我已经向Company表添加了一条记录(ID = 1),所以现在我想添加一条新的Car记录为

Car c = new Car { Name = "car1" };
c.CompanyId = 1;
context.Cars.Add(c);
context.SaveChanges();

above approach works, I'm OK with that, but if I try the following approach, then it doesn't work and throw an exception(cannot add explicit value to identify column: 上面的方法行得通,我可以,但是如果我尝试以下方法,则行不通并抛出异常(无法添加显式值来标识列:

Car c = new Car { Name = "car1" };
Company com = new Company { Id = 1 };
c.Company = com;
context.Cars.Add(c);
context.SaveChanges();

so why DbSet.Add() thinks I'm adding a new Company record? 那么为什么DbSet.Add()认为我要添加新的公司记录? can't it be smart enough to tell that there is already a company record whose id is 1 in the Company table? 难道不足够聪明,以至于在Company表中已经存在一个ID为1的公司记录?

It's because by default the Entity framework tries to add two objects to the database with a relationship between them when you are creating a relationship between two new objects. 这是因为在创建两个new对象之间的关系时,默认情况下,实体框架会尝试将两个对象及其之间的关系添加到数据库中。 You can prevent adding child objects with the: 您可以使用以下方法阻止添加子对象:

context.Entry(com).State = EntityState.Detached

or you can just try 或者你可以尝试

Car c = new Car { 
    Name = "car1",
    Company = context.Companies.First(x => x.Id == 1)
};

context.Cars.Add(c);
context.SaveChanges();

The DbContext instance will add the relationships on the entity as added (new) items in the database which will be added when the changes are persisted ( SaveChanges ). DbContext实例会将实体上的关系添加为数据库中的已添加(新)项,并在持久保存更改后将添加这些关系( SaveChanges )。 You can manually change the state back to Unchanged for any entity that does not have changes. 对于没有Unchanged的任何实体,您可以将状态手动更改回“未更改”。

Car c = new Car { Name = "car1" };
Company com = new Company { Id = 1 };
c.Company = com;
context.Cars.Add(c);

// mark the company as unchanged
context.Entry(com).State = EntityState.Unchanged;

context.SaveChanges();

Alternatively you can query the DbContext for an instance of Company and use that but this is 1 extra roundtrip to the database. 或者,您可以查询DbContext作为Company的实例,并使用它,但这是数据库的额外往返1次。 The upside of this approach is the code might be easier to read/maintain. 这种方法的好处是代码可能更易于阅读/维护。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM