具有标识''的成员在元数据集合中不存在.\ r \nParameter name:identity

And*_*tar 8 linq asp.net-mvc ado.net

我在尝试调试时简化了一些代码:

[HttpPost]
    public ActionResult Register(User model)
    {
        DateTime bla = new DateTime(2012, 12, 12);
        try
        {
            User user = new User
            {
                gid = 1,
                cid = 1,
                firstName = model.firstName,
                lastName = model.lastName,
                email = model.email,
                username = model.username,
                password = model.password,
                creationDate = bla,
                active = 1
            };
            myContext.Users.AddObject(user);
            myContext.SaveChanges();

        }
        catch (Exception ex)
        {
            throw ex;
        }

        return View();               
    }
Run Code Online (Sandbox Code Playgroud)

相应地传输这些值.用户表:

[id] [int] IDENTITY(1,1) NOT NULL,
[cid] [int] NULL,
[gid] [int] NULL,
[firstName] [nvarchar](100) NOT NULL,
[lastName] [nvarchar](100) NOT NULL,
[email] [nvarchar](max) NOT NULL,
[username] [nvarchar](100) NOT NULL,
[password] [nvarchar](100) NOT NULL,
[creationDate] [datetime] NOT NULL,
[active] [int] NOT NULL,
Run Code Online (Sandbox Code Playgroud)

CONSTRAINT [PK_ Users _3213E83F0AD2A005] PRIMARY KEY CLUSTERED

我删除了所有的外键,以确保没有任何影响它.我确定在前一刻它工作正常,但现在我无法确定问题所在.它在执行savechanges时崩溃:

{"An error occurred while updating the entries. See the inner exception for details."}
{"The member with identity '' does not exist in the metadata collection.\r\nParameter name: identity"}
Run Code Online (Sandbox Code Playgroud)

And*_*tar 8

问题是由于用户表上的触发器而重现.删除它,问题不再复制.


BTE*_*BTE 6

当我尝试使用EF插入时,我遇到了同样的错误,错误是

The member with identity 'Id' does not exist in the metadata collection.\r\nParameter name: identity

起初并不明显,但异常消息非常简洁,因为我的数据库知道列,Id int但是为我的代码上的对象创建的属性是int ID如此回到命名映射,Id未映射到ID.

因此,当具有属性的对象ID被发送到数据库时,只知道Id您将获得上述错误.

我希望这有帮助,谢谢

  • 可能最好从检查财产外壳的名称开始回答这个问题。我的在配置中为 Property(x => x.IdVersion).HasColumnName(@"IdVersion").HasColumnType("int").IsRequired().HasDatabaseGenerateOption(System.ComponentModel.DataAnnotations.Schema.DatabaseGenerateOption.Identity); 但它需要将 .HasColumnName 更改为 .HasColumnName(@"idVersion") 因为这是 SQLite 数据库定义中的内容 (2认同)

pas*_*k23 5

我认为最好的解决方案就在这篇文章中。我使用了第三个选项并且有效。这里我把链接里的回复汇报一下:

该问题可能与您的一张表上的“而不是插入”触发器有关。

EF 框架通过调用scope_identity() 对插入的数据行执行验证。但是,“而不是插入”触发器将更改插入的上下文,从而使 EF 系统对scope_identity 的调用将返回 null。

有几种方法可以解决这个问题:

  1. 使用存储过程插入数据(未测试)
  2. 删除代替插入触发器(触发器可能会导致其他问题,因此有些人认为不要使用它们)(经过测试,有效!)
  3. 关闭 EF 框架中的验证,因此: context.Configuration.ValidateOnSaveEnabled = false (经过测试,有效!)


Mil*_*vec 5

正在更新的表上可能有一个触发器,并且它返回输出。输出被丢弃,但与EF冲突。此类输出通常用于调试触发器(并忘记了以后删除):

select 'trigger called, i am here'
Run Code Online (Sandbox Code Playgroud)

或可能缺少变量:

select column 
Run Code Online (Sandbox Code Playgroud)

代替

select @variable=column 
Run Code Online (Sandbox Code Playgroud)