C# 如何管理数据库中的外键插入?

C# 如何管理数据库中的外键插入?,c#,linq-to-sql,foreign-keys,C#,Linq To Sql,Foreign Keys,我开发了一个小的对象解析器(用于SQL文件,它允许我轻松找到过程中使用的所有表的列表),我有以下模型: 3个表: 对象(ID、名称、LastWriteTime) 表(ID、名称) ObjectTable(ObjectID,TableID) 我有3个相应的类: 对象-扫描的文件列表: [Table(Name = "object")] public class SourceFile : IEquatable<SourceFile> { public SourceFile()

我开发了一个小的对象解析器(用于SQL文件,它允许我轻松找到过程中使用的所有表的列表),我有以下模型:

3个表:

  • 对象(ID、名称、LastWriteTime)
  • 表(ID、名称)
  • ObjectTable(ObjectID,TableID)
我有3个相应的类:

对象-扫描的文件列表:

[Table(Name = "object")]
public class SourceFile : IEquatable<SourceFile>
{
    public SourceFile()
    { }

    [Column(Name = "id", IsDbGenerated = true)]
    public Guid ID
    {
        get;
        set;
    }

    [Column(Name = "lastwritetime")]
    public DateTime LastWriteTimeUtc
    {
        get;
        set;
    }

    [Column(Name = "name", IsPrimaryKey = true)]
    public String Name
    {
        get;
        set;
    }

    public bool Equals(SourceFile other)
    {
        return Name == other.Name;
    }

    public override int GetHashCode()
    {
        return Name.GetHashCode();
    }
}
如您所见,object&table的ID是DBGenerated,所以我的问题是,如何使用生成的ID在ObjectTable中添加值?在DB中只插入一次,而不是之前


有什么提示吗?

如果您添加了已创建的实体对象,Linq to sql将为您找到答案。只要您的外键在DB中处于正常状态,类似的操作就会起作用:

using (db = new datacontext())
{ 
    var parent = new parent();
    var child = new child();
    parent.children.ad(child);
    db.parents.insertonsubmit(parent);
    db.submitchanges();
 }
因此,不添加关键点,而是添加对象。这同样适用于像你这样的协会

更新 在您的情况下,它看起来像(记在心里,所以请检查拼写错误)

}

或者您的问题是如何定义数据库中的外键?这是通过以下语句完成的:

ALTER TABLE ORDERS 
ADD FOREIGN KEY (customer_sid) REFERENCES CUSTOMER(SID); 

看起来不错,但是我怎么能说
父对象中的
子对象
是指表
对象表
using (db = new datacontext())
{ 
    var parent = new parent();
    var child = new child();
    parent.children.ad(child);
    db.parents.insertonsubmit(parent);
    db.submitchanges();
 }
using (db = new datacontext())
{
var o = new Object();
var t = new Table();
db.objects.insertonsubmit(o);
db.tables.insertonsubmit(t);
var objecttable = new objecttable();
objecttable.object = o;
objeecttable.tbale = t;
db.objecttables.insertonsubmit(objecttable);
db.submitchanges();
ALTER TABLE ORDERS 
ADD FOREIGN KEY (customer_sid) REFERENCES CUSTOMER(SID);