【问题标题】:Entity Framework Many to many saving create existing entity实体框架多对多保存创建现有实体
【发布时间】:2014-04-28 15:48:26
【问题描述】:

我有两个具有多对多关系的类。当我保存我的上下文时,Entity Framework 没有使用现有的 Id,它会在我的数据库中创建新条目。

我的课程如下:Country 和 CountryGroup(在我的数据库中,EF 按预期创建 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; }
}

我使用 ASP MVC 4 和 Entity Framework 5。当我想保存 CountryGroup 时,我使用网站中已有的国家/地区。 Id 是正确的。

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

我只希望 EF 保存我的对象以及与国家/地区的关系,而不是。我在这里有什么解决方案?我觉得我对 EF 管理多对多的方式有误解。

【问题讨论】:

    标签: asp.net-mvc-4 entity-framework-5 entity


    【解决方案1】:

    经过多次研究,我认为我的问题在于模型绑定器。它必须只创建对象而不从上下文中获取它们。我重写了我的 Save 方法,用上下文中的一个新的 CountryGroup 实体替换了每个 Country。这不是最优的,但我将研究模型绑定,然后我将在这些解决方案之间进行仲裁。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-26
      • 2016-10-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多