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

12

13

I simplified the code a little while trying to debug:

[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();               
    }

The values are transmited accordingly. Users table:

[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,

CONSTRAINT [PK_Users_3213E83F0AD2A005] PRIMARY KEY CLUSTERED

I deleted all the foreign keys to be sure that nothing affects it. I am qute certain that at a previous moment it was working, but now I can not figure where the issue is. It crashes while performing the 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"}
Fran answered 30/5, 2012 at 14:49 Comment(5)
Why you are instantiating a new User and setting the properties? You can directly set the not-binded properties to the model right?Bacterin
tried using the below solution(without instantiating a new User object) but is not working.Fran
Is the User model has property id?Bacterin
Is there any triggers set up in the table? Check prosoftnearshore.com/blog/post/2012/03/28/…Bacterin
It was because of a trigger. Thank you!Fran
F
11

The issue was reproducing because of a trigger that was on the users table. Removed it and the issue is not reproducing anymore.

Fran answered 31/5, 2012 at 8:49 Comment(2)
But what if the trigger is needed? I doubt a trigger was added randomly. I have 3 triggers on my view (not a table in this case), Insert, Update and Delete. But am only getting this error on the insert. (I access the data through a view, so the actions are carried out on the view, which is actually where the triggers reside.)Kalina
I have faced same issue. if I remove the trigger several function is now work. so I strongly need the trigger. how I Can keep the trigger but not produce the error ?Rejuvenate
T
12

I had the same error being thrown when I try to insert using EF, the error was

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

It wasn't obvious at first but the exception message was very concise because my database knows the column Id int but the property created for the object on my code was int ID so coming back to named mapping, Id is not mapped to ID.

So when an object with property ID is sent to database that only know Id you will get the above error.

I hope this helps, thanks

Topic answered 15/2, 2014 at 23:34 Comment(3)
Might be better to start this answer off with Check the name of the Casing of the property. Mine was in the Configuration as Property(x => x.IdVersion).HasColumnName(@"IdVersion").HasColumnType("int").IsRequired().HasDatabaseGeneratedOption(System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption.Identity); BUT it needed to have the .HasColumnName changed to .HasColumnName(@"idVersion") since that is what was in the SQLite database definitionDrachm
I don't know, how many hours we spent on this issue. But this post exactly solved it for us: as stated here, it turned out that the name of the identity column was case sensitive. So we renamed ID to Id in the base table, re-create the view with which we are working - and that solved it.Unexacting
This was also the case for a SQLite database. This answer saved me quite some headache!Around
F
11

The issue was reproducing because of a trigger that was on the users table. Removed it and the issue is not reproducing anymore.

Fran answered 31/5, 2012 at 8:49 Comment(2)
But what if the trigger is needed? I doubt a trigger was added randomly. I have 3 triggers on my view (not a table in this case), Insert, Update and Delete. But am only getting this error on the insert. (I access the data through a view, so the actions are carried out on the view, which is actually where the triggers reside.)Kalina
I have faced same issue. if I remove the trigger several function is now work. so I strongly need the trigger. how I Can keep the trigger but not produce the error ?Rejuvenate
S
8

There is probably a trigger on the table being updated and it returns output. The output is thrown away but it conflicts with EF. Such output is often used to debug triggers (and forgotten to delete later):

select 'trigger called, i am here'

or there can be missing variable:

select column 

instead of

select @variable=column 
Skyrocket answered 17/8, 2015 at 22:39 Comment(0)
F
5

I think that the best solution is in this post. I used the 3rd option and works. Here I report the reply in the link:

The issue could be related to a "instead of insert" trigger on one of your tables.

The EF framework is performing validation on the inserted row of data by calling scope_identity(). However, an "instead of insert" trigger will change the context of the insertion in such a way that the EF system's call to scope_identity will return null.

A couple ways around this:

  1. Use a stored procedure to insert the data ( not tested )
  2. Remove the instead of insert trigger ( triggers can cause other problems, so some people argue not to use them) ( tested, works!)
  3. Turn off validation in the EF framework, so: context.Configuration.ValidateOnSaveEnabled = false ( tested, works!)
Fraze answered 28/7, 2014 at 9:27 Comment(0)
C
1

I had this same error today and spent a few frustrating hours trying to figure it out.

I was using Entity Framework to insert a record with an identity column into a SQL server database table. Simple enough.

The table had a trigger on it which in turn ran a stored procedure. The stored procedure had a line in it:

select newid()

This is the line that broke Entity Framework.

For tables with identity columns, Entity Framework expects to be returned a single row with a single field that is the identity column.

Crimple answered 31/7, 2014 at 3:47 Comment(0)
Y
1

it's because of trigger pass back value to EF if you are using trigger. in my problem i must check a value by selecting from other table and using of 'select' cause error in EF, so you must replace 'select' with 'set'. you can not use this code.

select @any= any from tablename  

you should use set instead of select

set @any= (select any from tablename)
Yemane answered 5/11, 2018 at 19:10 Comment(1)
I tried this, but it made no difference. In my case it turned out that the name of the identity column was case sensitive. So I had to rename ID to Id in my base table, re-create the view with which we are working - and that solved it.Unexacting
K
1

Somedays, I hate M$.

The member with identity 'ChangeID' does not exist in the metadata collection. Parameter name: identity

I've spent two days trying to get around this.

I'm using MVC.

To get all the data I need in one fell swoop, I created a view of the table in the DB for this application, and tables in other databases. (You may update views, with some constraints.)

I do a get, and all my data is present in the record, keys, descriptions, foreign keys, etc.

I created triggers on my view, to update the portion of the view that came from the local table.

Instead of Delete worked fine. Instead of Update worked fine.

This error kept raising it's head on Instead of Insert. I could NOT get the insert trigger to successfully insert into my table. If I ran an insert on the view, with all fields provided in the SQL Management Studio, it worked fine. I know the exact values being passed because I ran SQL Server Profiler to see the code being passed.

But when the app attempted the update, it failed with The member with identity 'ChangeID' does not exist in the metadata collection.

Clue up above, someone said, "MVC expects table key to be ID"

I renamed ChangeID as ID in my view, changed it in the App, and BAM! Now it works.

What did NOT work:

  • db.Configuration.ValidateOnSaveEnabled = false;
  • adding a select to the trigger to get scope identity

Why do I have to modify my DB or my view to satisfy some hidden M$ assumption?

None the less, after two very frustrating days, code is now working. Maybe this will save someone else some time as well.

Kalina answered 31/1, 2020 at 23:19 Comment(0)
B
0

Try this

[HttpPost]
public ActionResult Register(User model)
{
    DateTime bla = new DateTime(2012, 12, 12);
    try
    {
        model.gid = 1;
        model.cid = 1;
        model.creationDate = bla;
        model.active = 1;

        myContext.Users.AddObject(model);
        myContext.SaveChanges();

    }
    catch (Exception ex)
    {
        Console.WriteLine(ex);
        throw;
    }

    return View();               
}
Bacterin answered 30/5, 2012 at 15:46 Comment(0)
C
0

I was having this issue and my fix, was that in my connection-string metadata I did not specify my model in the .msl format.

See more info here

Crocoite answered 23/3, 2018 at 14:1 Comment(2)
While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. - From ReviewDistort
@Distort Hi Liam, my answer is explaining how I missed the .msl part of my metadata, the link just further explains what and why that is an issue.Crocoite
T
0

You may use another context instead of User's Context. Ensure myContext is the correct one for User entity.

In my case, SetName of the entity was incorrect. Shortly, this worked for me:

Use

myContext.AddObject(nameOfSetEntity, user);

Instead of:

myContext.Users.AddObject(user);

To get the whole correct name of the entity (thanks to Nix's answer)

string className = typeof(User).Name;
var container = myContext.MetadataWorkspace.GetEntityContainer(myContext.DefaultContainerName, System.Data.Metadata.Edm.DataSpace.CSpace);
string nameOfSetEntity= (from meta in container.BaseEntitySets
                              where meta.ElementType.Name == className
                              select meta.Name).First();

Context.AddObject(nameOfSetEntity, user);
Traynor answered 22/2, 2023 at 15:14 Comment(0)
P
0

The error in my case was that I had a select statement inside the trigger, I eliminated it and it worked perfectly

Postdoctoral answered 25/5, 2023 at 14:21 Comment(1)
As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.Calore
P
0

I solved it on my end. I have a problematic trigger in sql. The trigger is the problem but I need to have it so I had really tried to make it work and then later on, I found the solution to this problem and this solved for me.

What I did was, I just removed all SELECT statement that will not assign a value to a variable and will just display messages or values. I just remove those and voila, problem solved!

Procrastinate answered 11/7, 2024 at 6:14 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.