EF代码优先和数据库视图 [英] EF Code First and Database Views

查看:158
本文介绍了EF代码优先和数据库视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



这里 Ladislav建议使用NotMapped继承父表和Db-View(我的视图只添加子实体的总和)...但是如何使用CF迁移?我真的想用它们



另外...导航属性可以在Db-View实体上工作?



有没有办法保存数据直接进入Db-View实体(和它的表)?

解决方案

如果要首先使用代码和迁移,使用视图。视图是数据库逻辑结构,代码首先不是创建数据库逻辑的方法。使用代码,您应该使用链接答案中提到的投影。



迁移将无法检测到与您的视图相关的更改。您将必须手动编写视图的所有迁移代码。



如果要使用视图,您应该首先执行数据库(=无迁移),并将其与EDMX或代码映射进行映射。


另外...导航属性可以在Db-View实体上工作?


这是代码映射提供比EDMX更好的支持的唯一场景。即使在数据库中不存在,也可以在模型中定义关系(但数据库必须确保数据完整性)。在理论上可以使用EDMX,但需要手动更改EDMX。


有没有办法将数据直接保存到Db-View实体(和它的表)?


是的,但你的视图必须是可更新的。我不认为具有聚合值的视图是可更新的。


I just started looking at Database Views with Code First... and try to decide if I should use them.

Here Ladislav recommends to use NotMapped inheritance parent for table and Db-View (my view only adds sums of child entities)... but how this work with CF Migrations? I really want to use them.

Also... navigation properties will work on Db-View Entity?

Is there any way to save data directly into Db-View entity (and it's table)?

解决方案

If you want to use code first and migrations you should not use views. Views are database "logic" constructs and code first is not an approach for creating database logic. With code first you should use the projection which is also mentioned in the linked answer.

Migrations will not be able to detect changes related to your views. You will have to write all migration code for views manually.

If you want to use views you should do database first (= no migrations) and either map them with EDMX or code mapping.

Also... navigation properties will work on Db-View Entity?

This is the only scenario where code mapping provides better support than EDMX. You can define relation in your model even if it doesn't exist in the database (but your database must ensure data integrity). It is in theory possible with EDMX as well but it requires changing EDMX manually.

Is there any way to save data directly into Db-View entity (and it's table)?

Yes but your view must be updatable. I don't think that view with aggregation values is updatable.

这篇关于EF代码优先和数据库视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆