我有一个简单的方法,我使用实体框架保存给出的客户信息导入数据库:将数据保存到数据库中使用实体框架,并返回新插入的标识
public Customer AddCustomer(Customer customer)
{
using (var context = DataObjectFactory.CreateContext())
{
context.AddObject("CustomerEntities", Mapper.Map(customer));
context.SaveChanges();
return customer;
}
}
客户类型是非常简单的,它由ID和客户名称,所以当我们想要保存客户时,我只需将客户对象传递给AddCustomer方法,此时Id为空,Name字段包含我要保存到数据库的名称。
这工作正常,名称被插入到数据库中,但是我想要做的是获取保存的客户标识并返回到调用函数,有没有实现这一点?
编辑:
这是所使用的映射方法:
internal static class Mapper
{
internal static IList<Customer> Map(IEnumerable<CustomerEntity> entity)
{
return entity.Select(Map).ToList();
}
internal static Customer Map(CustomerEntity entity)
{
return new Customer
{
CustomerId = entity.CustomerId,
Name = entity.Name
};
}
internal static CustomerEntity Map(Customer customer)
{
return new CustomerEntity
{
CustomerId = customer.CustomerId,
Name = customer.Name
};
}
}
感谢
您是否在调用SaveChanges后检查了'customer.Id'的值? –
那么它是否不会自动设置回Customer.Id? –
是的,检查了id,它仍然是空的。 – 03Usr