2012-09-27 28 views
1

我有一个简单的方法,我使用实体框架保存给出的客户信息导入数据库:将数据保存到数据库中使用实体框架,并返回新插入的标识

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 
     }; 
    } 
} 

感谢

+0

您是否在调用SaveChanges后检查了'customer.Id'的值? –

+0

那么它是否不会自动设置回Customer.Id? –

+0

是的,检查了id,它仍然是空的。 – 03Usr

回答

2

与映射部分有点怀疑,因为我们不知道是什么Mapper.Map(customer)不会返回..但我确信它确实会返回一个新的实例...所以customer.Id将不会更改,因为您不会将customer添加到上下文中,但Mapper.Map(customer)

编辑:好吧,我的猜测是正确的(什么天才;))。所以这应该是

public int AddCustomer(Customer customer) 
{ 
    using (var context = DataObjectFactory.CreateContext()) 
    { 
     var customerEntity = Mapper.Map(customer); 
     context.AddObject("CustomerEntities", customerEntity); 

     context.SaveChanges(); 

     return customerEntity.Id; 
    } 
} 
+0

感谢您的评论,我已将Mapper部分添加到该问题中。 – 03Usr

+0

@ 03Usr你试过我的代码吗?认为它应该可以工作 –

+0

@ 03Usr顺便说一句,它们是现有的映射库,比如AutoMapper。 –

相关问题