C# 如何在实体框架中基于2个外键生成复合键?
有可能这样做吗 若有,那个么在模型中定义这种场景的语法是什么 表1C# 如何在实体框架中基于2个外键生成复合键?,c#,entity-framework,C#,Entity Framework,有可能这样做吗 若有,那个么在模型中定义这种场景的语法是什么 表1 Key 1 表2 Key 2 表3 composite of Key 1, Key 2 从形式上讲,在数据库中不必有外键约束——您只需要外键。如果没有FK约束是您的情况,那么您仍然可以在EF中轻松地重现此结构(您没有提到EF版本,所以我使用EF6) 1。连接字符串 在使用显式加载时,您需要启用MARS连接以避免(请参见第4项): 3。EF上下文和类 public class StackOverflowContext : D
Key 1
表2
Key 2
表3
composite of Key 1, Key 2
从形式上讲,在数据库中不必有外键约束——您只需要外键。如果没有FK约束是您的情况,那么您仍然可以在EF中轻松地重现此结构(您没有提到EF版本,所以我使用EF6) 1。连接字符串 在使用显式加载时,您需要启用MARS连接以避免(请参见第4项): 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; }
}
希望这能澄清问题 可能的副本不完全相同。我已经试过了,但问题是,缺少与它们所尊重的表的关系约束。如果您说表3与其他两个表不相关,那么您需要处理FK映射。你可以用几种方法来做到这一点。按照约定,如果密钥名为Table1Id,则它将是表1的FK。您还可以使用
ForeignKey
属性或流畅的代码。与你的问题类似。有助于显示实际型号顺便说一句。是EF6还是EF Core?
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);
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; }
}
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;
}
}
}