0

I have two classes with a Many-to-Many relationship. When I save my context, Entity Framework is not using the existing Ids, it creates new entry in my database.

My classes are the following : Country and CountryGroup (in my database EF creates as expected CountryGroupCountries).

public class Country : EntityBase
{
    public Country()
    {
        CountryGroups = new List<CountryGroup>();
    }


    public virtual List<CountryGroup> CountryGroups { get; set; }
}

public class CountryGroup : EntityBase
{
    public CountryGroup()
    {
        Countries = new List<Country>();
    }

    public virtual  List<Country> Countries { get; set; }
}

public abstract class EntityBase
{
    public EntityBase()
    {
        DateCreate = DateTime.Now;
        DateUpdate = DateTime.Now;
        DateDelete = DateTime.Now;
    }

    [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    [Timestamp]
    public byte[] RowVersion { get; set; }

    [Required]
    public virtual String Name { get; set; }
}

I use ASP MVC 4 and Entity Framework 5. When I want to save a CountryGroup, I use Countries that are already in my website. The Ids are the right one.

    public virtual void Save(TEntity entity)
    {
        EntityRepository.Insert(entity);
        Context.SaveChanges();
    }

I just want EF to save my object and the relation to the countries but not. What solution do I have here ? I Feel like I have a misunderstanding of the way EF manages Many To Many.

1 Answer 1

0

After many research I believe that my problem lies on the model binder. It must be only creating object without getting them from the context. I overridded my Save Method to replace each Countries in the CountryGroup entity with a fresh one from the context. It is not optimal but I'm going to studie the model binding and then I will arbitrate between those solutions.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.