【问题标题】:Entity Framework - How to access foreign key not listed in Model实体框架 - 如何访问模型中未列出的外键
【发布时间】:2015-02-04 15:38:21
【问题描述】:
我有以下两个实体,
public class App
{
public int AppID { get; set; }
public string Business { get; set; }
public string ApName { get; set; }
public string FirstContact { get; set; }
}
public class Colleague
{
public int ColleagueID { get; set; }
public string FirstName { get; set; }
public string SecondName { get; set; }
public string EmailAddress { get; set; }
public int PhoneNumber { get; set; }
public virtual ICollection<App> Apps { get; set; }
}
在我的 SQL 表中,这会自动为引用 ColleagueID 的 App 模型创建一个外键属性。
我的问题是,由于实际模型中没有提到外键,我如何在查询中使用它?例如,我想显示外键与给定同事 ID 匹配的所有应用程序。
【问题讨论】:
标签:
c#
entity-framework
model-view-controller
foreign-keys
【解决方案1】:
你在正确的轨道上。您需要为App 类填充外键。这是一对多关系的完美示例。
public class App
{
public int AppID { get; set; }
public string Business { get; set; }
public string ApName { get; set; }
public string FirstContact { get; set; }
[ForeignKey("Colleague")]
public int ColleagueId { get; set; }
public virtual Colleague Colleague { get; set; }
}
然后你可以在任何你想要的地方拨打App.CollegueId或App.Colleague.CollegueId。
【解决方案2】:
一个解决方案是:
IQueryable<Apps> q = ctx.Colleagues.Where(x => x.ColleagueID == someId).
SelectMany(x => x.Apps);
您不会在生成的 SQL 查询中看到支持 Colleague 的表。你会得到类似的东西:
SELECT
[Extend1].[AppID] AS [AppID],
...
FROM [dbo].[Apps] AS [Extend1]
WHERE 123 = [Extend1].[Colleague_ColleagueID]
Colleague_ColleagueID 由 EF 处理且仅由 EF 处理
因此,出于您给出的原因,没有必要在您的班级中公开 FK。
【解决方案3】:
此外,如果您不想使用 Data Annotations 并希望在将 App 保存到 DB 时将 Colleague 设为可选,则可以使用 Fluent Api。首先,将ColleagueId FK 属性添加到您的App 类中:
public class App
{
//...
public int? ColleagueId { get; set; }
}
然后在你的 Context 上覆盖 OnModelCreating 方法:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<App>()
.HasOptional(a => a.Colleague)
.WithMany(c => c.Apps)
.HasForeignKey(a => a.ColleagueId);
}
现在,您可以这样查询:
int selectedColleagueId = 1;
var apps=context.Apps.Where(a => a.ColleagueId == selectedColleagueId);
但是,正如@tschmit007 在他的回答中显示的那样,如果您只想搜索该值,则无需公开 FK。当您需要更新关系时,FK 属性非常有用,例如,当您在内存中可能没有 Coleague 对象,但您确实可以访问该对象的键值时。使用外键属性,您可以简单地使用键值,而无需依赖该实例在内存中:
app.ColleagueId=3;
context.SaveChanges();