我有一个基类Person:
[KnownType(typeof(Doctor))]
public abstract class Person
{
public int PersonId { get; set; }
public string FirstName { get; set; }
public string MiddleName { get; set; }
public string LastName { get; set; }
public string Gender { get; set; }
public DateTime BirthDate { get; set; }
public string Email { get; set; }
public string MobilePhoneNumber { get; set; }
public string HomePhoneNumber { get; set; }
public bool IsGlobal { get; set; }
public bool IsDeleted { get; set; }
public bool IsApproved { get; set; }
public int? FacilityId { get; set; }
public int? AddressId { get; set; }
public virtual FacilityView Facility { get; set; }
public virtual Address Address { get; set; }
public virtual ICollection<Organization> Organizations { get; set; }
public virtual ICollection<TenantEntity> TenantEntities { get; set; }
}
并拥有嵌套类Doctor:
public class Doctor : Person
{
public string Speciality { get; set; }
}
表人脚本
CREATE TABLE [core].[Person](
[PersonId] [int] IDENTITY(1,1) NOT NULL,
[Discriminator] [nvarchar](255) NOT NULL,
[FirstName] [nvarchar](255) NOT NULL,
[MiddleName] [nvarchar](255) NULL,
[LastName] [nvarchar](20) NOT NULL,
[Gender] [nvarchar](20) NOT NULL,
[BirthDate] [date] NOT NULL,
[Email] [nvarchar](250) NULL,
[MobilePhoneNumber] [nvarchar](250) NULL,
[HomePhoneNumber] [nvarchar](250) NULL,
[IsGlobal] [bit] NOT NULL,
[IsDeleted] [bit] NOT NULL,
[IsApproved] [bit] NOT NULL,
[FacilityId] [int] NULL,
[AddressId] [int] NULL,
[Speciality] [nvarchar](250) NULL,
当我尝试保存新的Doctor实体时,我有一个错误:
无法将值NULL插入列&#39; Discriminator&#39;
在这种情况下我做错了什么?为什么EF不能保存&#34;医生&#34; Discriminator字段中的值?
更新:
部分来自DBContext:
public DbSet<Person> Persons { get; set; }
#region Person
modelBuilder.Entity<Person>()
.ToTable("Person", "core")
.HasKey(t => t.PersonId);
modelBuilder.Entity<Person>()
.HasOptional(t => t.Facility);
modelBuilder.Entity<Person>()
.HasOptional(t => t.Address);
modelBuilder.Entity<Person>()
.HasMany(x => x.Organizations)
.WithMany()
.Map(x =>
{
x.MapLeftKey("PersonId");
x.MapRightKey("OrganizationId");
x.ToTable("PersonOrganization", "core");
});
modelBuilder.Entity<Person>()
.HasMany(x => x.TenantEntities)
.WithMany()
.Map(x =>
{
x.MapLeftKey("PersonId");
x.MapRightKey("TenantEntityId");
x.ToTable("PersonTenantEntity", "core");
});
#endregion
答案 0 :(得分:4)
如果只存在一个派生类,则默认继承映射不会定义鉴别器列。 如果定义派生自Person的第二个类,则代码将起作用:
public class Nurse : Person
{
public string Whatever {get;set;}
}
或者将鉴别器明确添加到您的模型中。
modelBuilder.Entity<Doctor>().Map(p => p.Requires("Discriminator").HasValue("Doctor"));