Manoj Pagdhune
Manoj Pagdhune

Reputation: 41

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

We are using EF Code First 4.3.1. We are developing an ASP.NET Web Role referring to multiple class libraries. There are two class libraries each containing classes and an individual DBcontext.

Lets say the Library1 has classes A and B. DBcon1: DbSet and DbSet

Lets say the Library2 has classes C and D. Class C{ [Key] public int CId{ get; set;}

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

When I try to use the DBcon2 as such:

        using (var con = new DBcon2())
        {
            C vr = new C();
            vr.CId= 1;
            vr.referencedA = DBCon1.As.First();
            con.Cs.Add(vr);
            con.SaveChanges();
        }

I get an exception as: "The member with identity does not exist in the metadata collection. Parameter name: identity"

Both DBCon1 and DBcon2 are using the sane SQL Server Database "SampleDB".

Please point me in the right direction.

Upvotes: 4

Views: 9180

Answers (2)

stuartdotnet
stuartdotnet

Reputation: 3034

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

eg

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
}

Might not be your issue but maybe it will point you in the right direction and hopefully will help someone else.

Upvotes: 4

Gert Arnold
Gert Arnold

Reputation: 109165

The exception is a bit cryptic, but pretty clear if you realise that a context needs information about entities (metadata) to be able to write sql statements. Thus, your DBcon2 context has no clue where to find the primary key of an A, because it has no metadata about A.

You could however set an integer property A_Id (or the like), but then you'll have to write custom code to resolve it to an A.

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

Upvotes: 1

Related Questions