简体   繁体   English

使用Entity Framework将视图中的字段映射到我的模型并将其设置为只读

[英]Mapping a field from a view to my model using Entity Framework and setting it as read only

I am using Entity Framework code-first (non auto generated) and I am trying to map some properties in my OnModelCreating event. 我正在使用Entity Framework代码优先(非自动生成),并且尝试在OnModelCreating事件中映射一些属性。 Most properties are from a SQL Server table however there is a field I want to include in my model from a view, I have done this and set it as [DatabaseGenerated(DatabaseGeneratedOption.Computed)] . 大多数属性来自SQL Server表,但是我想从视图中将其包含在模型中,我已完成此操作并将其设置为[DatabaseGenerated(DatabaseGeneratedOption.Computed)]

However EF tries to update the view, how do I tell EF to not update my view and treat it as read only, the error I get is... 但是EF尝试更新视图,我如何告诉EF不要更新视图并将其视为只读,我得到的错误是...

Cannot update the view or function 'VIEWNAME' because it contains aggregates, or a DISTINCT or GROUP BY clause, or PIVOT or UNPIVOT operator 无法更新视图或函数“ VIEWNAME”,因为它包含聚合,DISTINCT或GROUP BY子句或PIVOT或UNPIVOT运算符

I can see plenty of things to make your view update-able but no to just treat it as read only 我可以看到很多东西可以使您的视图变为可更新状态,但不能仅将其视为只读

UPDATE 更新

After trying a few things I have added [DatabaseGenerated(DatabaseGeneratedOption.Identity)] to the property when defining it in my model and this seems to have done the trick, seems a bit strange though as setting it as Identity doesn't make much sense to me over setting it as computed but seems to be working. 在尝试了几件事之后,我在模型中定义属性时将[DatabaseGenerated(DatabaseGeneratedOption.Identity)]到了属性中,这似乎已经成功了,尽管将它设置为Identity并没有多大意义,但似乎有些奇怪对我来说,将其设置为计算值,但似乎可行。

did you try this on your properties? 您是否在房产上尝试过?

public virtual string MyProperty { get; internal set; }

this way the entity consumer cannot change it. 这样,实体消费者无法更改它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在不使用实体框架的情况下,仅将来自不同模型的必需字段/属性调用到 asp.net mvc 5 中的视图模型中 - call only required field/attribute from the different models into a view model in asp.net mvc 5 without using entity framework 实体框架映射到查看读取和CUD表 - Entity framework mapping to view for read and to table for CUD 在Entity Framework 7中为整个模型仅映射一次公共属性 - Mapping Common Properties only once for the whole Model in Entity Framework 7 当我从现有数据库创建模型时,Entity Framework 4.0 生成只读模型 - Entity Framework 4.0 generating read only model when I create model from existing database 具有实体框架模型映射的MVC - MVC with Entity Framework Model Mapping 实体框架-使用视图模型的“ GetAll”功能 - Entity Framework - A 'GetAll' function using a View Model 实体框架 - 从视图创建模型? - Entity Framework - Create a model from a view? 读取“实体框架的最大长度”字段并分配给Razor视图中的文本框 - Read Maximum length of Entity Framework field and assign to textbox in Razor View 实体框架6代码首先更改从视图到新表的映射 - entity framework 6 code first change mapping from view to new table 使用数据库中的更新模型添加只读视图 - Adding a Read-Only View using Update Model from database
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM