c# - 带空值的 EF Core 复合主键

标签 c# asp.net-core-mvc ef-core-2.2

只是想知道这是否可能:我有一个来自现有数据库的表,我无法修改。我只对查看数据感兴趣。我不会更新表格。

没有主键。有两个键组合在一起会使行唯一。不幸的是,这两列都允许并具有空值。

我试过:

 modelBuilder.Entity<IesHrEmployee>(entity => {
                entity.HasKey(o => new { o.PERS_NO, o.POS_NO });
                entity.ToTable("IES_HR_EMPLOYEES", "DBO");
            });

不幸的是在我的仓库中

public class IesHrEmployeesRepository : IIesHrEmployeesRepository
{
        private DataContext context;

        public IesHrEmployeesRepository(DataContext ctx) => context = ctx;

        public IEnumerable<IesHrEmployee> IesHrEmployees => context.IesHrEmployees.ToArray();
}

toArray 调用中,我收到此错误:

Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[2]
Executed action UserNavigator.Controllers.IesHrController.Index (UserNavigator) in 139.9397ms fail:
Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware[1]

An unhandled exception has occurred while executing the request. System.Data.SqlTypes.SqlNullValueException: Data is Null. This method or property cannot be called on Null values.

at System.Data.SqlClient.SqlBuffer.get_String()
at System.Data.SqlClient.SqlDataReader.GetString(Int32 i)

最佳答案

不,您不能从可为空的列组成主键。然而,如果你只需要查询这个表(没有插入或更新),你可以创建一个 DbQuery<IesHrEmployee>您的上下文中的属性,根本不需要 key 。

关于c# - 带空值的 EF Core 复合主键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57579999/

相关文章:

c# - 覆盖对象返回值

asp.net-core-mvc - 如何使用 Swashbuckle 的 SwaggerUI 来显示静态 swagger.json 文件而不是 SwaggerGen 的动态创建的定义?

postgresql - 如何使用 Entity Framework 核心为 postgres 数据库安装 TimescaleDB 扩展

c# - 尝试获取用于在 ASP.NET Core MVC 中播种数据的注入(inject)服务

c# - 在不破坏不变性的情况下更改属性值

c# - IDataReader 和 "HasColumn",最佳方法?

c# - c# 可以像 VB.NET 一样自动更正语法大小写吗?

asp.net-core - IdentityServer v4 的 ASP.NET Core 客户端中的通知

每个请求的 ASP.NET 5 (VNext) Autofac 实例

c# - 同时执行两个数据库调用(使用两个 DbContext)