问题描述
您好我在更新相关实体时遇到问题。所以我的Document实体有一组Customers。当我添加一个新文档时,我可以添加尽可能多的客户,但是当我更新时,只更新标量属性。
这是我更新文档的代码...
Hello I have a problem when updating related entities. So my Document entity has a collection of Customers. When Im adding a new document I can add as many customers as I want, but when Im updating only scalar properties are updated.
This is my code for updating a document...
public static bool UpdateDocument(Document documentToUpdate)
{
using (MyDbContext = new MyDbContext())
{
// attaching the entity does not help
if (context.Entry(documentToUpdate).State == EntityState.Detached)
context.Documents.Attach(documentToUpdate);
context.Entry(documentToUpdate).State = EntityState.Modified;
context.SaveChanges();
return true;
}
}
关于文档操作,添加和删除客户的废话是在另一个层/项目中完成的,所以我的问题是我如何继续这个?或者如何在此方法中更新相关的客户集合?或者shuld我使用不同的方法只是为了客户操作。
类似
Evrything regarding document manipulation, adding and removing customers is done in another layer/project, so my question is how shuld I proceed with this? Or how do I update the related customer collection here in this method? Or shuld I use a different method just for customer manipulation.
Something like
public static void UpdateCustomersOnDoc(Document doc)
{
using (MyDbContext context = new MyDbContext())
{
Document tempDoc = DocumentCRUD.GetByID(doc.Id);
// remove the customers from the document (database)
tempDoc.Customers.Clear();
// add customers from the modified document
foreach(var cust in doc.Customers)
{
docTemp.Customers.Add(cust);
}
// save changes to the context
context.SaveChanges();
}
}
推荐答案
public static bool UpdateDocument(Document documentToUpdate)
{
using (MyDbContext = new MyDbContext())
{
Document doc = MyDbContext.FirstOrDefault(d=> d.ID == documetToUpdate.ID)
//
//
CopyUserInputData(documentToUpdate, doc); //You should implement this method that save user input in the given "doc" object!
context.SaveChanges();
return true;
}
}
这篇关于Enitiy框架更新相关实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!