Item with id does not exist in the metadata collection. Parameter name: identifier

We are using EF Code First 4.3.1. We are developing an ASP.NET Web Role by referencing several class libraries. There are two class libraries, each containing classes and a separate DBcontext.

Suppose library 1 has classes A and B. DBcon1: DbSet and DbSet

Let's say library 2 has classes C and D. Class C {[Key] public int CId {get; install;}

public virtual A referencedA {get; set;}
DBcon2: DbSet<C> and DbSet<D>


When I try to use DBcon2 as such:

        using (var con = new DBcon2())
            C vr = new C();
            vr.CId= 1;
            vr.referencedA = DBCon1.As.First();


I am getting an exception: "Item with identity does not exist in the metadata collection. Parameter name: identity

Both DBCon1 and DBcon2 use the standard SQL Server "SampleDB" database.

Please point me in the right direction.


source to share

2 answers

I got this error and fixed it by not trying to set navigation property on related table, just set foreign key id instead


public class Student()
    public int StudentId { get; set; }
    public string StudentName { get; set; }
    public int CourseId { get; set; }
    public virtual Course Course { get; set; }

public class Course()
    public int CourseId { get; set; }
    public string CourseName { get; set; }
    public virtual ICollection<Student> Students { get; set; }


Main code:

var myCourse = new Course();
var myCourseId = 1;

var student = new Student() {
    CourseId = myCourseId
    // Course = myCourse <-- this would cause the error


It may not be your problem, but it might point you in the right direction and hopefully help someone else.



The exception is a bit cryptic, but pretty clear if you understand that the context needs information about objects (metadata) in order to be able to write SQL statements. So your DBcon2 context has no idea where to find the primary key A

because it has no metadata about A.

However, you can set the integer A_Id property (or the like), but then you have to write your own code to resolve it A


Another option is to merge (parts of) contexts, if possible.



All Articles