具有标识"Id"的项目已存在于元数据集合中.参数名称:item

bea*_*dev 6 c# entity-framework entity-framework-6

我的所有实体都有一个基类:

public class Entity<TKey> : IEntity<TKey>
{
    dynamic IEntity.Id
    {
        get
        {
            return this.Id;
        }
        set
        {
            this.Id = value;
        }
    }

    public TKey Id { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

例如状态实体:

[MetadataType(typeof(StatusMetadata))]
public partial class Status : Entity<byte>
{
       public string Title { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

当我对数据库运行查询时,我收到以下错误:"具有标识'Id'的项已经存在于元数据集合中.参数名称:item".有没有办法解决这个问题,或者这是由继承引起的问题,我不能从任何类继承我的实体?

Ale*_*dro 5

这似乎是一般错误,寻找一些见解,我看到:

Two tables can have the same name for a primary key. Look at the LightSwitch tables, they all have a primary key called Id.

http://social.msdn.microsoft.com/Forums/vstudio/en-US/bd8d47da-d1b4-4be8-a7e5-193fb5360060/the-item-with-identity-actionpk-already-exists-in-the-metadata -collection?论坛=电灯开关

因此,我查看了所有实体,并获得了一个更改了Identiy数据类型的实体,并继承了另一个具有int Id属性的类.

我是否将此更改public new string Id { get; set; }public string Id { get; set; }喜欢其他人并删除继承,一切正常.


Nie*_*els 5

原因是您从已经具有不同类型的Id属性的类继承.

我在CodeMigrations中看到了同样的错误.我有一个名为"Version"的属性为string的属性,我继承的EntityData数据类也包含byte []类型的Version属性.这会产生与您提到的相同的错误

解决方案是不要使用基类中已有的相同属性名称.

  • 我在使用EF 6.1.2时遇到了这个问题.我升级到EF 6.1.3,问题神奇地消失了. (6认同)

小智 -1

尝试将“new”添加到属性中,如下所示:

[MetadataType(typeof(StatusMetadata))]
public partial class Status : Entity<byte>
{
       public new string Title { get; set; }
}
Run Code Online (Sandbox Code Playgroud)