我有一个通用的业务类,我用它来操纵我的数据与mysql 5.6和实体框架6.我创建了一个方法,从表中导入数据并创建一个对象列表,这样我就可以调用业务类并保存或更新目标数据库中的记录。
//part of import method
using (var business = new Business<Customer>(context))
{
foreach (var sourceCustomer in sourceCustomersList)
{
var customer = business.GetData().ToList().Find(x=>x.OriginalId == sourceCustomer.Id) ?? new Customer();
customer.Name = sourceCustomer.Name; // for example, this property is required
customer.Fone = sourceCustomer.Fone;
customer.City = sourceCustomer.City;
customer.State = sourceCustomer.State);
customer.Active = sourceCustomer.Active;
if (customer.Id > 0)
{
business.Update(Customer);
}
else
{
customer.SourceId = sourceCustomer.Id;
business.Insert(fornecedor);
}
}
}
public class Business<T> : IBusiness<T>, IDisposable
{
protected ESistemContext Context;
public Business(ESistemContext context)
{
Context = context;
}
public virtual bool Insert(T entity)
{
try
{
Context.Entry(entity).State = EntityState.Added;
Context.SaveChanges();
return true;
}
catch (Exception exception)
{
return false;
}
}
public virtual bool Update(T entity)
{
try
{
Context.Entry(entity).State = EntityState.Modified;
Context.SaveChanges();
return true;
}
catch (Exception exception)
{
return false;
}
}
public void Dispose()
{
if (Context == null)
return;
Context.Dispose();
Context = null;
}
}
我的问题是:当我对项目有一个验证错误(Name属性的空值)时,我尝试处理的所有其他项目在调用时都有相同的验证错误(即使它们正确填充了Name属性) context.SaveChanges()调用异常的业务类,并显示相同的验证错误。
答案 0 :(得分:0)
Context.Entry(entity).State = EntityState.Detached;