在EF4中, 提供了FK Properties 和 FK Associations的支持,对于association没有了于table mapping的概念,只需要映射到2个实体的属性上.没有FK Properties 的association被称作为Independent Association 。因此最近一周断断续续看了几篇关于FK associations的文章.我不想过多的转述那几篇blog中提到的为何在EF4中做出这样的变化.在EF Design team blog上可以看到许多国外朋友对于FK association的利用与弊的讨论.正因为如此,EF Design team
才采取了一种折中的做法,同时支持FK Properties 和FK association.
下面是我对FK Properties 和FK association所作的练习:
表Department,Course,外键关系
在EF4.0中
生成的EDM:
|
|
EF4.0还不支持Hierarchyid
双击Assocaition 可以看到下面的窗口,但在vs2008 sp1里面是看不到的,不过在vs2010中选中或不选中include foreign key column in the model
还是有区别的:
因为上图的不同所以,edmx的xml文件也不一样:主要是在csdl中的xml不一样;
选中 include foreign key;
下面的内容是关于如何在程序中使用FKAssociation,IndependentAssociation
static void InsertDepartmentFKAssociation()
{
using (FKAssociation.FKAssociationEntities2 context = new FKAssociation.FKAssociationEntities2())
{
FKAssociation.Deparment d = new Deparment {
DepartmentID=Guid.NewGuid(),
Budget="budget",
Name="ist",
StartDate=DateTime.Now,
Administrator="administrator" };
FKAssociation.Course c = new Course {
CourseID=Guid.NewGuid(),
DepartmentID=d.DepartmentID,
Status="status",
Title="title" };
context.AddToDeparments(d);
context.AddToCourses(c);
context.SaveChanges();
}
}
static void InsertDepartmentIndependentAssociation()
{
using (FKAssociation.FKAssociationEntities2 context = new FKAssociation.FKAssociationEntities2())
{
FKAssociation.Deparment d = new Deparment
{
DepartmentID = Guid.NewGuid(),
Budget = "budget",
Name = "ist",
StartDate = DateTime.Now,
Administrator = "administrator"
};
FKAssociation.Course c = new Course
{
CourseID = Guid.NewGuid(),
DepartmentID = d.DepartmentID,
Status = "status",
Title = "title",
Deparment=d,
};
d.Courses.Add(c);
context.SaveChanges();
}
}
在使用的时候 其实有很多细节可以体现出2者的不同。在一个edm中的Association是可以更据实际情况来决定是否使用IndependentAssociation 还是FKAssociation。
参考文献
http://blogs.msdn.com/efdesign/archive/2009/03/16/foreign-keys-in-the-entity-framework.aspx
entity framework 4.0 recipes
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· 周边上新:园子的第一款马克杯温暖上架
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?
· 使用C#创建一个MCP客户端