是否可以这样做?
如果是,那么在模型
中定义此类场景的语法是什么表1
Key 1
表2
Key 2
表3
composite of Key 1, Key 2
答案 0 :(得分:0)
正式地说,在数据库中没有强制要求外键约束 - 您只需要外键。如果没有FK约束,那么你仍然可以轻松地在EF中重现这个结构(你没有提到EF版本,所以我使用的是EF6)。
<强> 1。连接字符串
使用显式加载时,您需要启用MARS连接以避免this error(参见第4项):
<configuration>
<connectionStrings>
<add name="StackOverflowContext"
providerName="System.Data.SqlClient"
connectionString="Server=(localdb)\mssqllocaldb;Database=StackOverflow;Trusted_Connection=Yes;MultipleActiveResultSets=True;" />
</connectionStrings>
</configuration>
<强> 2。用于创建测试表和种子的T-SQL:
create table dbo.Table1 (Table1Id int primary key);
create table dbo.Table2 (Table2Id int primary key);
create table dbo.Table3 (Table1Id int, Table2Id int);
insert into dbo.Table1 values (10), (20);
insert into dbo.Table2 values (30), (40);
insert into dbo.Table3 values (10, 30);
insert into dbo.Table3 values (20, 40);
第3。 EF上下文和类
public class StackOverflowContext : DbContext
{
public DbSet<Table1> Table1 { get; set; }
public DbSet<Table2> Table2 { get; set; }
public DbSet<Table3> Table3 { get; set; }
}
[Table("Table1")]
public class Table1
{
public int Table1Id { get; set; }
}
[Table("Table2")]
public class Table2
{
public int Table2Id { get; set; }
}
[Table("Table3")]
public class Table3
{
// Composite key of two keys
[Key, Column(Order = 1)]
public int Table1Id { get; set; }
[Key, Column(Order = 2)]
public int Table2Id { get; set; }
// Navigation properties
public Table1 Table1 { get; set; }
public Table2 Table2 { get; set; }
}
<强> 4。从表3中获取数据
现在从Table3获取数据,但不是直接读取属性Table1Id
和Table2Id
,而是通过导航属性。为此,我使用显式加载:
private void OnRun(object sender, EventArgs e)
{
using (var db = new StackOverflowContext())
{
var t3 = db.Table3;
foreach (Table3 t in t3)
{
// Explicit loading
db.Entry(t).Reference(p => p.Table1).Load();
// Get Table1Id through navigation property
int id = t.Table1.Table1Id;
}
}
}
希望这将清除图片!