我有一个POCO曾经用EF
正确填充public class CompanyToggle
{
public Guid CompanyId { get; private set; } // CompanyId (Primary key)
public int ToggleId { get; private set; } // ToggleId (Primary key)
public bool IsEnabled { get; private set; } // IsEnabled
// Foreign keys
/// <summary>
/// Parent Company pointed by [CompanyToggle].([CompanyId]) (FK_CompanyToggle_Company)
/// </summary>
public virtual Company Company { get; private set; }
/// <summary>
/// Parent Toggle pointed by [CompanyToggle].([ToggleId]) (FK_CompanyToggle_Toggle)
/// </summary>
public virtual Toggle Toggle { get; private set; }
// For EF
private CompanyToggle()
{ }
}
然后我添加了另一个Ctor:
public CompanyToggle(Guid companyId, int toggleId, bool isEnabled)
{
this.CompanyId = companyId;
this.ToggleId = toggleId;
this.IsEnabled = isEnabled;
}
我的Fluent API绑定是这样的:
public class CompanyToggleConfiguration: EntityTypeConfiguration<CompanyToggle>
{
public CompanyToggleConfiguration()
: this("dbo")
{
}
public CompanyToggleConfiguration(string schema)
{
ToTable("CompanyToggle", schema);
HasKey(x => new { x.CompanyId, x.ToggleId });
Property(x => x.CompanyId).HasColumnName(@"CompanyId").HasColumnType("uniqueidentifier").IsRequired().HasDatabaseGeneratedOption(System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption.None);
Property(x => x.ToggleId).HasColumnName(@"ToggleId").HasColumnType("int").IsRequired().HasDatabaseGeneratedOption(System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption.None);
Property(x => x.IsEnabled).HasColumnName(@"IsEnabled").HasColumnType("bit").IsRequired();
// Foreign keys
HasRequired(a => a.Company).WithMany(b => b.CompanyToggles).HasForeignKey(c => c.CompanyId).WillCascadeOnDelete(true); // FK_CompanyToggle_Company
HasRequired(a => a.Toggle).WithMany(b => b.CompanyToggles).HasForeignKey(c => c.ToggleId).WillCascadeOnDelete(true); // FK_CompanyToggle_Toggle
}
}
添加新的公共Ctor后,从上下文加载对象只加载CompanyId
和ToggleId
,并使Toggle和Company对象都为空。
我可以通过将CompanyToggle无参数Ctor公开来修复它,但我想将它保密。
知道为什么来自EF的这种行为?在我看来,EF正在寻找最容易接近的Ctor!