gpt4 book ai didi

entity-framework - Entity Framework 4 中的更新对象,需要一直先取吗?

转载 作者:行者123 更新时间:2023-12-04 08:30:25 26 4
gpt4 key购买 nike

我可能完全错了,但是使用 EF4 的简单插入和更新让我发疯。(EF 新手)

我创建了一个 noddy 项目并上传到这里

http://cid-9db5ae91a2948485.office.live.com/browse.aspx/PublicFolder?uc=1http://cid-9db5ae91a2948485.office.live.com/browse.aspx/PublicFolder?uc=1

如果您喜欢并解决问题,请随意下载。这太棒了。

简而言之,我希望有人告诉我,我怀疑的情况并非如此。

假设您有一个客户对象。在更新之前是否需要像删除一样先获取它?这对我来说似乎很疯狂。

鉴于您有一个保存方法(插入和更新都在这里完成)并且您将客户传递给它。您已经拥有所有详细信息。您将如何修改以使其工作?我收到各种错误。
每次我需要修改客户的 child 时,我都需要去数据库吗?

   public void Save(CustomerDTO customerDTO)
{
//convert dto to EF entity
var entityCustomer=ToEntityCustomer(customerDTO)
using(ctx=new CustomerContext())
{

if(efCustomer.CustomerId > 0)
{
//UPDATE

//DO I NEED TO FETCH MY CUSTOMER AGAIN FROM THE DB EVEN THOUGH I ALREADY HAVE
//HAVE ALL THE DETAILS? I have not done it here.?????

ctx.Customers.Attach(entityCustomer);
ctx.ApplyCurrentValues(entityCustomer);

//Also Customer has addresses so
foreach(var address in entityCustomer.Addresses)
{
//some may be new addresses some might be modified one
?????? lost
}

}
else
{
///INSERT
ctx.Customers.AddObject(entityCustomer);
ctx.ObjectStateManager.ChangeObjectState(entityCustomer,EntityState.Added);
foreach(var address in entityCustomer.Addresses)
{
ctx.ObjectStateManager.ChangeObjectState(address ,EntityState.Added);
}
}

ctx.SaveChanges();
}
}

最佳答案

如果您不想在保存之前获取对象,这是一种方法:

public bool Save(CustomerInfo customerInfo)
{
var entityCustomer = ToEntityCustomer(customerInfo);
using (var ctx = new CustomerContext())
{
ctx.ContextOptions.LazyLoadingEnabled = false;
DataAccess.Address[] addresses = new DataAccess.Address[entityCustomer.Addresses.Count];
entityCustomer.Addresses.CopyTo(addresses, 0);
entityCustomer.Addresses.Clear();

if (customerInfo.Id == 0) {
ctx.Customers.AddObject(entityCustomer);
}
else if (customerInfo.Id > 0) {
ctx.Customers.Attach(entityCustomer);
ctx.ObjectStateManager.ChangeObjectState(entityCustomer, EntityState.Modified);
}

foreach (var address in addresses) {
if (address.AddressID == 0) {
ctx.Addresses.AddObject(address);
entityCustomer.Addresses.Add(address);
}
else if (address.AddressID > 0) {
ctx.Addresses.Attach(address);
ctx.ObjectStateManager.ChangeObjectState(address, EntityState.Modified);
if (customerInfo.Id == 0) {
// New Customer so we need to add the existing addresses
// since the FK on Address is 0
entityCustomer.Addresses.Add(address);
}

}
}
ctx.SaveChanges();
return true;
}
}

诀窍是在父对象(例如客户)上执行附加/添加对象之前删除子对象(例如地址),因为这两个操作会影响整个图,并且会导致各种问题。

关于entity-framework - Entity Framework 4 中的更新对象,需要一直先取吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4237005/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com