我开发了一个小对象解析器(对于允许我轻松查找过程中使用的所有表的列表的SQL文件),我有以下模型:
3张表:
我有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();
}
}
表 - 数据库中所有表的列表:
[Table(Name = "table")]
public class SourceTable : IEquatable<SourceTable>
{
public SourceTable()
{ }
[Column(Name = "id", IsDbGenerated = true)]
public Guid ID
{
get;
set;
}
[Column(Name = "name", IsPrimaryKey = true)]
public String Name
{
get;
set;
}
public bool Equals(SourceTable other)
{
return Name == other.Name;
}
public override int GetHashCode()
{
return Name.GetHashCode();
}
}
ObjectTable - 对于每个对象,使用的表列表:
[Table(Name = "object_table")]
public class SourceFileTable
{
[Column(Name = "object_id", IsPrimaryKey = true)]
public Guid ObjectID
{
get; set;
}
[Column(Name = "table_id", IsPrimaryKey = true)]
public Guid TableID
{
get; set;
}
}
正如您所看到的,对象的ID和&amp; table是DBGenerated,所以我的问题是,如何使用生成的ID在ObjectTable中添加值?只有在DB中插入一次,而不是之前。
任何提示?
答案 0 :(得分:0)
如果添加已创建的实体对象,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();
}
所以你不要添加键而是添加对象。这同样适用于像你这样的协会。
更新的 在你的情况下,它看起来像(心脏,所以请检查拼写错误)
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);