实体框架:在哪里扩展 CSDL/MSL?
我正在使用 Entity Framework 4。我正在使用数据库优先模型,这意味着我从数据库生成了 EDM。现在我想添加一些模型定义的函数。我的问题是……在哪里?
如果我将它们放入 .edmx 文件中,那么下次更新数据库并生成新的 EDM 时,我添加的所有内容是否都会被破坏?我的意思是它就在 .Designer.cs 文件的顶部说:“如果重新生成代码,对此文件的手动更改将被覆盖。”
那么,我应该将添加内容放在哪个文件中?
I'm using Entity Framework 4. I am using a database first model, meaning that I generated the EDM from the database. Now I want to add some model-defined functions. My question is ... where?
If I put them in the .edmx file, won't all my additions be clobbered the next time I update the database and generate the new EDM? I mean it says it right there at the top of the .Designer.cs file, "Manual changes to this file will be overwritten if the code is regenerated."
So, in what file do I put my additions?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我会稍微深入一点,因为模型定义的函数并不是很为人所知。
模型定义的函数必须手动添加到 EDMX 文件的 CSDL 部分。您必须以 XML 格式打开文件并添加函数。例如,此模型定义的函数能够生成员工的全名:
现在您可以保存 EDMX 并返回给设计者。该功能仍然存在,但在模型浏览器中不可见。您可以从数据库更新模型或删除所有实体,但函数仍将被定义。 EF 不会删除 EDMX 的 CSDL 部分中的自定义修改。
现在您需要定义 .NET 函数才能使用此模型定义的函数。你可以在任何地方做。一种方法是使用部分类来上下文,但同时您可以只使用一些自定义类:
这样就完成了。剩下的唯一任务是在 Linq-to-Entities 查询中使用该函数:
模型定义的函数只是一些可重用的 Entity SQL,它们被转换为 SQL,因此只能在 Linq-to-Entities 查询中使用。模型定义的函数可能要复杂得多。
I will take it little bit deeply because model defined functions are not very well known.
Model defined functions must be manually added to CSDL part of EDMX file. You must open file as XML and add a function. For example this model defined function is able to produce full name of the employee:
Now you can save your EDMX and return to designer. The function will be still present but it is not visible in Model browser. You can update your model from database or delete all your entities but the function will be still defined. EF doesn't remove custom modification in CSDL part of EDMX.
Now you need to define the .NET function to be able to use this model defined function. You can do it anywhere. One way is to use partial class to context but in the same time you can just use some custom class:
And you are done. The only remaining task is using the function in Linq-to-Entities query:
Model defined functions are just some reusable Entity SQL which is translated to SQL so they can be only used in Linq-to-Entities queries. Model defined functions can be much more complicated.