简体   繁体   中英

EF Core composite primary key with nulls

Just wondering if this is possible: I have a table from an existing database I can not modify. I am only interested in viewing the data. I will not be updating the table.

There is no primary key. There are two keys that when combined would make the row unique. Unfortunately both of these columns allow, and have null values.

I tried:

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

Unfortunately in my repository

public class IesHrEmployeesRepository : IIesHrEmployeesRepository
{
        private DataContext context;

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

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

on the toArray call, I get this error:

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)

No, you cannot compose a primary key from nullable columns. However, if you just need to query this table (no inserts or updates), you can create a DbQuery<IesHrEmployee> property on your context, without requiring a key at all.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM