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"}
Andrei Spatar
  • 253
  • 1
  • 3
  • 10
  • Why you are instantiating a new User and setting the properties? You can directly set the not-binded properties to the model right? – VJAI May 30 '12 at 15:45
  • tried using the below solution(without instantiating a new User object) but is not working. – Andrei Spatar May 30 '12 at 17:19
  • Is the User model has property id? – VJAI May 31 '12 at 03:20
  • 1
    Is there any triggers set up in the table? Check http://www.prosoftnearshore.com/blog/post/2012/03/28/The-member-with-identity-does-not-exist-in-the-metadata-collection-Parameter-name-identity.aspx – VJAI May 31 '12 at 03:26
  • It was because of a trigger. Thank you! – Andrei Spatar Jun 01 '12 at 06:19

11 Answers11

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

Biniam Eyakem
  • 545
  • 5
  • 18
  • 2
    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 definition – Matt Vukomanovic Jan 01 '20 at 09:49
  • 1
    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. – Tillito Apr 23 '21 at 09:35
  • 1
    This was also the case for a SQLite database. This answer saved me quite some headache! – 321X Mar 22 '22 at 14:24
11

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

Andrei Spatar
  • 253
  • 1
  • 3
  • 10
  • 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.) – ARLibertarian Jan 31 '20 at 22:35
  • 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 ? – farid wahyu Mar 28 '22 at 03:59
7

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 
Milan Švec
  • 1,675
  • 17
  • 21
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!)
pask23
  • 714
  • 11
  • 20
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.

Nick
  • 146
  • 1
  • 7
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)
  • 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. – Tillito Apr 23 '21 at 09:34
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.

ARLibertarian
  • 155
  • 1
  • 11
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();               
}
Marcel Gosselin
  • 4,610
  • 2
  • 31
  • 54
VJAI
  • 32,167
  • 23
  • 102
  • 164
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

Cœur
  • 37,241
  • 25
  • 195
  • 267
  • 1
    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 Review](/review/low-quality-posts/19209534) – Liam Mar 23 '18 at 14:31
  • 1
    @Liam 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. – Joshua Simon Bloom Mar 23 '18 at 14:46
0

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);
0

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

Beto
  • 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](/help/how-to-answer). – Community May 25 '23 at 19:07