我有一個簡單的方法,我使用實體框架保存給出的客戶信息導入數據庫:將數據保存到數據庫中使用實體框架,並返回新插入的標識
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