【问题标题】:The entity type 'List<PersonAddress>' was not found. Ensure that the entity type has been added to the model找不到实体类型“List<PersonAddress>”。确保实体类型已添加到模型中
【发布时间】:2018-03-06 19:27:08
【问题描述】:

我正在使用 .net core 2.0 构建应用程序。我有一个带有地址列表的 Person 对象。地址存储在地址表中。然后我有一个将人员与地址相关联的连接表。

class Person {
    public List<PersonAddress> Addresses { get; set; } 
}

class Address {
    ...address properties...
}

class PersonAddress{
    public int AddressId { get; set; }
    public Address Address { get; set; }

    public int PersonId { get; set; }
    public Person Person { get; set; }
}

当我使用包含地址的 PersonAddress 保存 Person 对象时,效果很好。它在连接表中插入一个新人、一个新地址和一条新记录。 (我在fluent api中配置了关系)。

但是,当我尝试更新时,我遇到了问题。在加载人员对象及其地址列表后,我可以添加、删除或更改地址,并且不会跟踪更改。

我在我的控制器中尝试了这个以使其处理更改:

dbContext.Entry(person.Addresses).State = EntityState.Modified;

我得到这个错误:

The entity type 'List&lt;PersonAddress&gt;' was not found. Ensure that the entity type has been added to the model.

毫无疑问,它在模型上,所以我不知道为什么这不起作用。我试过这个:

person.Addresses.ForEach(item => _context.Entry(item).State = EntityState.Modified);

它没问题,但这不跟踪添加或删除,所以这还不够。

【问题讨论】:

  • 没有 List 类型的实体。 entry 方法检索该对象的 DbEntityEntry,但是列表绝不是模型的一部分,因为它们通常只是具有其他类型的多个实体的导航属性。 “跟踪添加或删除”只是 changetracker 所做的事情,但它不能在断开连接的情况下追溯。要么让 changetracker 跟踪 List 并在不重新附加的情况下完成其工作,要么使用适当的 .Add、.Entry().State=Modified/Deleted 方法。
  • @user3413723 你应该分享你的解决方案:)
  • 请分享您的解决方案
  • 请分享您的解决方案 +1
  • 我也遇到了同样的问题,能否分享一下解决方法

标签: .net entity-framework .net-core


【解决方案1】:

我的问题是我有一个

var listOfItems = await DbContext.Items.ToListAsync();
DbContext.Remove(listOfItems);

看了第二次(第 10 次)后,我意识到我需要将其更改为:

var listOfItems = await DbContext.Items.ToListAsync();
DbContext.RemoveRange(listOfItems);

所以只需要从 Remove 更改为 RemoveRange

【讨论】:

    【解决方案2】:

    在我的例子中,该方法是异步的,我收到了错误,因为我省略了“await”关键字。见附件图片,可能会有所帮助。

    Added the await keyword

    Entity type not found error

    【讨论】:

    【解决方案3】:

    这里有一些代码可以区分现有地址和用户提交的地址。

    // first, get a list of the items currently in the database
    // make sure to get asNoTracking so we don't run into any weird issues
    var currentList = db.Addresses.Where(item => item.PersonId == person.Id)
        .AsNoTracking().Select(item => item.AddressId);
    // get a list of the ids in the newly submitted list
    var newList = person.Addresses.Select(item => item.AddressId);
    
    var newItemIds = newList.Except(currentList);
    var deletedItemIds = currentList.Except(newList);
    var updatedItemIds = newList.Intersect(currentList);
    
    // now you have Ids of all that have been added, removed and updated
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-15
      • 1970-01-01
      • 1970-01-01
      • 2014-12-03
      • 2016-02-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多