none
Add entity in Entity Framework Insert Null Record RRS feed

  • Question

  • Hi,

    I'm trying to insert a new Entity in EF:

    public class Ad
    {
        // Primary properties
        public int Kms { get; set; }
    
        // Navigation properties
        public virtual Model Model { get; set; }
    }

    And I receive from the View the model like this (example values):

    kms = 222 Model.Id = 3

    Then when I do the Add and SaveChanges of the Entity Framework, I get a NULL record inserted in the Model Table (that generated a new ID) and a record in the Ad Table with the new inserted Model Id.

    Why is this happening?

    Thanks.

    Thursday, October 25, 2012 2:02 AM

Answers

  • Hi,

    Thank you (for the welcome message).

    I found an answer, the problem was that I needed to attach the Model Entity first before creating the new Ad Record in the Database.

    This way it's working like a charme:

            public void CreateAd(CreateAdDto adDto)
            {
                var adDomain = Mapper.Map<CreateAdDto, Ad>(adDto);

                _modelRepository.Attach(adDomain.Model);

                _adRepository.Add(adDomain);
                _adRepository.Save();
            }

    Thanks.

    Friday, October 26, 2012 9:20 AM

All replies

  • Hi Patrick,

    Welcome to the MSDN forum.

    Could you please show me some code snippet about creating object and assigning value?

    On my side, I tried this:

                    var mdl = new Model { Id = 3 };
                    var ad = new Ad { Kms = 222, Model = mdl };
                    context.Ads.Add(ad);
                    context.SaveChanges();

    Have a nice day.


    Alexander Sun [MSFT]
    MSDN Community Support | Feedback to us

    Friday, October 26, 2012 2:58 AM
  • Hi,

    Thank you (for the welcome message).

    I found an answer, the problem was that I needed to attach the Model Entity first before creating the new Ad Record in the Database.

    This way it's working like a charme:

            public void CreateAd(CreateAdDto adDto)
            {
                var adDomain = Mapper.Map<CreateAdDto, Ad>(adDto);

                _modelRepository.Attach(adDomain.Model);

                _adRepository.Add(adDomain);
                _adRepository.Save();
            }

    Thanks.

    Friday, October 26, 2012 9:20 AM