gpt4 book ai didi

c# - EntityState 修改后的 SaveChanges 不保存

转载 作者:行者123 更新时间:2023-11-30 17:39:20 25 4
gpt4 key购买 nike

public static Result SaveCutomer(Customer customer)
{
using (AshdorEntities context = new AshdorEntities())
{
try
{
Contact con = null;
if (customer.customerId == 0)//new customer
{
customer.enterDate = DateTime.Now;
customer.Contact.dateEnter = customer.enterDate;
con = context.Contact.Add(customer.Contact);
customer.Contact = con;
customer.customerId = con.contactId;

}
else
context.Customer.Attach(customer);

context.Entry(customer).State = con != null ?
EntityState.Added :
EntityState.Modified;
context.SaveChanges();
}
catch
{
return new Result() { status = false, massege = MassegesResult.ADDING_FAILED };
}

return new Result() { status = true, massege = MassegesResult.ADDING_SUCCESSFUL };
}
}

最佳答案

这不是一个可行的解决方案……而是试图通过指出流动性不佳的部分来提供帮助....

public static Result SaveCutomer(Customer customer)
{
using (AshdorEntities context = new AshdorEntities())
{
try
{
//assumption is that its always a disconnected entity if not you will need to check
context.Customer.Attach(customer);

//this seems wrong as well
Contact con = null;

customer.enterDate = DateTime.Now;

//this seems wrong as well
customer.Contact.dateEnter = customer.enterDate;

//this seems wrong as well
con = context.Contact.Add(customer.Contact);

customer.Contact = null;
//this seems wrong as well
customer.customerId = con.contactId;

if (customer.customerId == 0)//new customer
{
context.Entry(customer).State = EntityState.Added
}
else //existing
{
context.Entry(customer).State = EntityState.Modified;
}
context.SaveChanges();
}
catch
{
return new Result() { status = false, massege = MassegesResult.ADDING_FAILED };
}

return new Result() { status = true, massege = MassegesResult.ADDING_SUCCESSFUL };
}
}

关于c# - EntityState 修改后的 SaveChanges 不保存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35626970/

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