0

To create a new BaseClass I only want to assign the Id's C2NumberId and C1NumberId.

Data structure:

[Table("BaseClass")]
public class BaseClass
{
    [Key]
    public Guid Id { get; set; }
    public string SomeProperty { get; set; }

    [ForeignKey("C1")]
    public int C1NumberId { get; set; }
    public virtual C1 C1 { get; set; }


    public BaseClass()
    {
        Id = Guid.NewGuid();
        C1 = new C1();
    }
}


[Table("C1")]
public class C1
{
    [Key]
    public int C1NumberId { get; set; }
    public string C1Name { get; set; }

    [ForeignKey("C2")]
    public int C2NumberId { get; set; }
    public virtual C2 C2 { get; set; }


    public C1()
    {
        C2 = new C2();
    }

}

[Table("C2")]
public class C2
{
    [Key]
    public int C2NumberId { get; set; }
    public string C2Name { get; set; }
}

Database schema:

here

Access DBContext:

using (XDBTestingContext db = new XDBTestingContext())
{ 
    BaseClass bc = new BaseClass();

    bc.C1NumberId = 1;// I already have that Id, table is just for look up 
    bc.SomeProperty = "dksal";

    bc.C1.C1NumberId = 1; // I already have that Id, table is just for look up 
    bc.C1.C2.C2NumberId = 1; // I already have that Id, table is just for look up 

    db.BaseClass.Add(bc);
    //db.BaseClass.Entry(bc).State = EntityState.Detached;
    //db.BaseClass.Entry(bc).State = EntityState.Modified;
    db.SaveChanges();
}   

Error:

'The instance of entity type 'C2' cannot be tracked because another instance with the same key value for {'C2NumberId'} is already being tracked. When attaching existing entities, ensure that only one entity instance with a given key value is attached. Consider using

I have read that I have to change the state (take a look at my comments), but it does not seem to work. Actually I just want to assign the existing Id to C2NumberId or C1NumberId, without loading the entire object.

How should it look the right way?

  • EF Core has limitation for navigation properties. https://stackoverflow.com/a/20773057/10646316 – Svyatoslav Danyliv Apr 04 '21 at 08:22
  • Remove `C1 = new C1();` from the constructor. If you already have the classes you shouldn't create new instances of them. And, as said, this should never be done in constructors. All you need is `bc.C1NumberId = 1`. – Gert Arnold Apr 04 '21 at 09:09

0 Answers0