Entity Framework code-first: querying a view with no primary key

帅比萌擦擦* 提交于 2020-01-06 01:29:12

问题


Our customer has given the access to views in which there is no primary key is defined. I know Entity Framework needs a primary key for table to identify.

But for views not having primary key is it still possible to query.

I try to find but always Entity Framework gives error saying:

Error: : EntityType 'ViewWeight' has no key defined. Define the key for this EntityType.

I understand key is important for tables, but for views just to read is there any hack or way to read the values without modifying the view itself.


回答1:


It's not possible in Entity Framework to have Entities without primary key.

Try to get a possible unique key from the views, combining columns, ... to create a unique primary key.

If is not possible there is a workaround, if is only a queryable view, with out need to do other operations with retrieved values such delete or update. Modify the view to add NEWID() , it will generate a unique GUID ID for each row, use this new column as primary key for your entity.

CREATE VIEW FooView AS
    SELECT SELECT SYS_GUID() AS ID,
           COLUMN_A,
           COLUMN_B
     .....

The problem is if you repeat the same query every time you will get different ID for the same row.

Updated

If you can't not modify the view you can use Entity with a raw Sql, create the raw sql as

List<MyView> myViewItems = context.MyView.SqlQuery("SELECT SYS_GUID() AS ID, MyView.* FROM MyView").ToList();

In your models add

public Guid ID { get; set; }

And configure the new property as the primary key.

But be careful, because there is not compilation check with this kind of code.




回答2:


I create the view which includes a primary key. Ensure that all fields in the view are of a specific data type:

Number(9) rather than Number, use CAST to get the type you want

Then add a disabled primary key constraint. It won't do anything except be recognized by entity framework as a key

alter view emp_view add constraint vemp_pk primary key (empno) disable


来源:https://stackoverflow.com/questions/30987474/entity-framework-code-first-querying-a-view-with-no-primary-key

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!