public class MyDbContext : DbContext
{
public DbSet Table1s { get; set; }
public DbSet Table2s { get; set; }
// ...
}
[Table("Table1", Schema = "Schema1")]
public class Table1
{
public int Id { get; set; }
public string Name { get; set; }
// ...
}
[Table("Table2", Schema = "Schema2")]
public class Table2
{
public int Id { get; set; }
public string Description { get; set; }
public int Table1_Id { get; set; }
// ...
}
[ForeignKey]
数据注解指定外键名称和关联表和列的名称:[Table("Table2", Schema = "Schema2")]
public class Table2
{
public int Id { get; set; }
public string Description { get; set; }
[ForeignKey("Table1Reference")]
public int Table1_Id { get; set; }
public virtual Table1 Table1Reference { get; set; }
// ...
}
PM> Add-Migration MyMigration
PM> Update-Database
public void AddTable2ToTable1(int table1Id, Table2 table2)
{
var table1 = _dbContext.Table1s.Find(table1Id);
table1.Table2s.Add(table2);
_dbContext.SaveChanges();
}
此时,在 Schema2 中表2 的数据表中 "Table1_Id" 一列将成为外键。