我正在開發一個小型web應用程序,並決定使用實體框架(v6.1.x)Code First。 我想創建一個新的數據庫條目 - 一個「offer」。在「要約」類別中,要約所屬的「客戶」也被存儲。EF代碼優先:爲什麼實體在找到它之後分離?
好吧,沒什麼特別的,我猜... 在我創建一個新的報價之前,我從數據庫中檢索客戶。 我創建了新的報價並設置了客戶屬性。在上下文中調用SaveChanges之後,我在客戶數據庫中重複了客戶。在做了一些調試之後,我發現客戶實體具有EntryState Detached ...爲什麼?
下面是一些代碼片段:
MVC控制器
var customer = default(Customer);
if (model.SelectedCustomerID > 0)
customer= _customerRepository.FindById(model.SelectedCustomerID);
// create new instance of offer
var offer = new Offer
{
// set all necessary properties
// ...
Customer = customer
}
_offerRepository.AddOffer(offer);
_offerRepository.Save();
客戶Repository.cs
private readonly IDatabaseContext _context;
// DatabaseContext is injected by AutoFac
public CustomerRepository(IDatabaseContext context)
{
_context = context;
}
public CustomerFindById(long id)
{
return _context.Customer.Find(id);
}
OfferRepository.cs
private readonly IDatabaseContext _context;
// DatabaseContext is injected by AutoFac
public OfferRepository(IDatabaseContext context)
{
_context = context;
}
public void AddOffer(Offer offer)
{
// _context.Entry(offer.Customer) --> Detached
_context.Offers.Add(offer);
}
老實說,我無法理解爲什麼客戶入口是分離的。 有人可以幫助我嗎?
被'IDatabaseContext'注入作爲一個單?如果不是 - 那麼注入兩個不同的上下文,當然不會附加來自另一個上下文的實體。 – ieaglle
我的猜測是'Customer'和'Offer'來自2個不同的上下文。 – SOfanatic