1

我有一个简单的方法,我使用实体框架将给定的客户信息保存到数据库中:

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

            context.SaveChanges();

            return customer;
        }
    }

客户类型很简单,它由客户的 ID 和名称组成,所以当我们要保存客户时,我只需将客户对象传递给 AddCustomer 方法,此时 ID 为空,名称字段包含我的名称想保存到数据库。

这工作正常,名称被插入到数据库中,但是我想要做的是取回保存的客户 ID 并返回到调用函数,有没有办法实现这一点?

编辑:

这是使用的 Mapper 方法:

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

谢谢

4

1 回答 1

2

对映射部分有一点疑问,因为我们不知道Mapper.Map(customer)会返回什么......但我很确定它确实返回了某个东西的新实例......所以customer.Id不会改变,因为你没有t 添加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;
    }
}
于 2012-09-27T11:38:37.190 回答