【问题标题】:Issue with Entity Framework, the table or view does not have a primary key实体框架问题,表或视图没有主键
【发布时间】:2021-08-06 06:19:16
【问题描述】:

我在 ASP.NET MVC 中有一个使用实体框架的小型 crud 应用程序,一切正常,只是要求我使用视图添加到 crud。在任何情况下,这个视图都没有主键,当我想添加视图时,它会跳转到我这个错误。有什么办法可以在不修改视图的情况下解决这个问题?

我附上示例视图:

create view view_Prueba 
as
    select nombre, garantia, region, sucursal
    from region, prueba
    where idprue = idprue

【问题讨论】:

  • Bad habits to kick : using old-style JOINs - 旧式 逗号分隔的表格列表 样式已替换为 ANSI 中的 proper ANSI JOIN 语法-92 SQL 标准(近 30 年前),不鼓励使用它
  • @marc_s 谢谢指正,不过是个例子,我无法访问服务器的真实视图

标签: c# asp.net asp.net-mvc entity-framework crud


【解决方案1】:
  1. 使用您的选择查询或使用 EF 在您的数据库中创建视图
context.Database.ExecuteSqlRaw(
@"Create view view_Prueba as
select nombre, garantia, region, sucursal
from region, prueba
where idprue=idprue");
  1. 创建 View_Prueba 类,其中包含 nombre, garantia, region, sucursal 属性 { get;私人套装; }

  2. 将此视图添加到您的 ef dbcontext

public virtual DbQuery<View_Prueba> View_Pruebas { get; set; }

.....


  modelBuilder.Entity<View_Prueba>(e =>
            {
                e.ToView("View_Prueba");
                e.HasNoKey();
            }); 

如果你使用 ef core version less then core 5 试试这个代码


public virtual DbQuery<View_Prueba> View_Pruebas { get; set; }

.....

【讨论】:

  • 我相信 .HasNoKey() 功能仅在 EF Core 中可用 - 我没有看到 OP 提到 EF 的“核心”版本的迹象 ....
  • @marc_s 是正确的,我没有使用 EF Core
猜你喜欢
  • 1970-01-01
  • 2011-04-29
  • 2010-11-04
  • 1970-01-01
  • 2015-09-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多