1

I have a simple method where I save the given customer information into the database using entity Framework:

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

            context.SaveChanges();

            return customer;
        }
    }

Customer type is very simple, it consists of Id, and Name of the customer, so when we want to save a customer I simply pass a customer object to AddCustomer method, at this point the Id is null and the Name field contains the name I want save to the database.

This works fine, the name gets inserted into the database, however what I want to do is to get the saved customer Id back and return to the calling function, is there anyway of achieving this?

EDIT:

This is the Mapper method used:

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

Thanks

3
  • Have you checked the value of customer.Id after the call to SaveChanges? Commented Sep 27, 2012 at 11:33
  • Is it not automatically being set back on Customer.Id then? Commented Sep 27, 2012 at 11:34
  • Yes, checked the id and it is still null. Commented Sep 27, 2012 at 11:39

1 Answer 1

2

have a little doubt with the Mapping part, as we don't know what Mapper.Map(customer) does return... But I'm quite sure that it does return a new instance of something... So customer.Id won't be changed, as you don't add customer to context, but Mapper.Map(customer)

EDIT : well, my guess was right (what a genius ;) ). So that should be

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

        context.SaveChanges();

        return customerEntity.Id;
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Tthanks for the comment, I have added the Mapper part to the question.
@03Usr they are fine existing mapping libraries, like AutoMapper, by the way.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.