【问题标题】:Executing stored procedure in Entity Framework - has no key defined. (Code First)在实体框架中执行存储过程 - 没有定义键。 (代码优先)
【发布时间】:2021-07-05 20:42:43
【问题描述】:

我正在尝试使用实体框架在 ASP.NET MVC 中执行存储过程。存储过程在返回的数据行中不返回任何唯一键。

我收到此错误:

类型:System.Data.Entity.ModelConfiguration.ModelValidationException, EntityFramework, Version=6.0.0.0

消息:在模型生成过程中检测到一个或多个验证错误:

SPProject.DTO.Result: : EntityType 'Result' 没有定义键。定义此 EntityType 的键。

结果:EntityType:EntitySet 'Results' 基于没有定义键的类型 'Result'。

实体类:

public class Result
{
    public string prop1 { get; set; }
    public string prop2 { get; set; }
    public string prop3 { get; set; }
    public string prop4 { get; set; }
}

数据库上下文:

public class ResultDBContext : DbContext
{
    public DbSet<Result> Results { get; set; }
}

控制器:

using (var context = new ResultDBContext())
{
    var input1 = new SqlParameter("@q1", q1);
    var input2 = new SqlParameter("@q2", q2);
    var input3 = new SqlParameter("@q3", "%");

    var result = context.Results
                .SqlQuery("[dbo].[sp] @q1, @q2, @q3", input1, input2, input3)
                .ToList();
}

我读到了关于使用复杂类型而不是实体来映射没有键的存储过程的输出,但不知道如何做到这一点。

【问题讨论】:

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


    【解决方案1】:

    给类添加 notmapped 属性

    [NotMapped]
    public class Result
    {
       ......
    }
    

    如果您使用旧的 .net,您可以尝试在结果中添加一个键列

    如果您使用网络核心,则添加到 dbcontext 的 OnModelCreating

      modelBuilder.Entity<Result>(e =>
                {
                    e.HasNoKey();
                });
    

    【讨论】:

    • 假设我必须在这里使用 EF Core,对吧?
    • 我以前使用过 [NotMapped],但它给了我一个不同的错误。 modelBuilder 是 EF Core 的一部分,这带来了一系列不同的问题。 Message : No database provider has been configured for this DbContext. A provider can be configured by overriding the DbContext.OnConfiguring method or by using AddDbContext on the application service provider. If AddDbContext is used, then also ensure that your DbContext type accepts a DbContextOptions&lt;TContext&gt; object in its constructor and passes it to the base constructor for DbContext.
    • 由于您决定使用不受支持的旧版框架,因此您必须使用一种解决方法。是什么阻止您向 Result 类添加更多属性?将此属性作为键并绑定到您的 sp 结果。
    • 但我的结果没有关键字段(它只返回 4 个字符串字段)并且它们都不是唯一键
    • 改变你的存储过程,添加一个主键列来选择。它会比尝试另一种方式更快、更有效。
    猜你喜欢
    • 1970-01-01
    • 2018-01-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-28
    • 1970-01-01
    • 2011-07-25
    • 1970-01-01
    相关资源
    最近更新 更多