Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/87.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 使用查找表中的Id创建新的数据库条目_C#_Sql_Entity Framework Core_Entity Relationship - Fatal编程技术网

C# 使用查找表中的Id创建新的数据库条目

C# 使用查找表中的Id创建新的数据库条目,c#,sql,entity-framework-core,entity-relationship,C#,Sql,Entity Framework Core,Entity Relationship,要创建一个新基类,我只想分配Id的C2NumberId和C1NumberId 数据结构: [Table("BaseClass")] public class BaseClass { [Key] public Guid Id { get; set; } public string SomeProperty { get; set; } [ForeignKey("C1")] public int C1NumberId {

要创建一个
新基类
,我只想分配Id的
C2NumberId
C1NumberId

数据结构:

[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; }
}
数据库架构:

访问数据库上下文:

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();
}   
错误:

'无法跟踪实体类型为'C2'的实例,因为另一个实体类型为'C2' 已创建与{'C2NumberId'}具有相同键值的实例 跟踪。附着现有实体时,请确保只有一个实体 附加了具有给定键值的实体实例。考虑使用

我读到我必须改变状态(看看我的评论),但它似乎不起作用。 实际上,我只想将现有Id分配给
C2NumberId
C1NumberId
,而不加载整个对象


它看起来应该如何正确?

EF Core对导航属性有限制。移除
C1=新的C1()来自构造函数。如果您已经拥有这些类,则不应该创建它们的新实例。如前所述,这永远不应该在构造函数中完成。您只需要
bc.c1numberrid=1