面对EF Core 2的一个奇怪问题。
我的联系模式:
public class Contact
{
public int Id { get; set; }
public int ExternalCustomerKey { get; set; }
public string Firstname { get; set; }
public string Surname { get; set; }
public DateTime DateOfBirth { get; set; }
public string Postcode { get; set; }
public DateTime WhenCreated { get; set; }
public List<ContactPreference> Preferences { get; set; }
}
ContactPreferene Model:
public class ContactPreference
{
public int Id { get; set; }
public int PreferenceTypeId { get; set; }
public DateTime WhenCreated { get; set; }
public DateTime LastModified { get; set; }
public int CustomerId { get; set; }
public Contact Contact { get; set; }
}
从数据库中检索联系人:
using (var context = new PreferenceServiceContext(_options))
{
var repository = new ContactRepository(context);
var contact = repository.FindContact(1);
}
返回联系人,首选项为null:
检查正在加载首选项的数据库上下文:
然后在联系人中加载首选项:
如果我不检查上下文,则首选项将为null。任何人都会遇到这个或任何建议。感谢
更新
更新1:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
// -- Map relationships
modelBuilder.Entity<Contact>(entity =>
{
entity.ToTable("Contact", "Preference");
entity.HasKey(e => e.Id);
entity.Property(e => e.ExternalCustomerKey).HasColumnName("ExternalCustomerKey");
entity.Property(e => e.Firstname).HasColumnName("Firstname");
entity.Property(e => e.Surname).HasColumnName("Surname");
entity.Property(e => e.DateOfBirth).HasColumnName("DateOfBirth");
entity.Property(e => e.Postcode).HasColumnName("Postcode");
entity.Property(e => e.WhenCreated).HasColumnName("WhenCreated");
entity.HasMany(e => e.Preferences).WithOne(e => e.Contact);
});
modelBuilder.Entity<ContactPreference>(entity =>
{
entity.ToTable("ContactPreference", "Preference");
entity.HasKey(e => e.Id);
entity.Property(e => e.CustomerId).HasColumnName("CustomerId");
entity.Property(e => e.PreferenceTypeId).HasColumnName("PreferenceTypeId");
entity.Property(e => e.WhenCreated).HasColumnName("WhenCreated");
entity.Property(e => e.LastModified).HasColumnName("LastModified");
entity.Property(e => e.AgentId).HasColumnName("AgentId");
entity.HasOne(e => e.Contact).WithMany(e => e.Preferences);
});
答案 0 :(得分:3)
检查正在加载首选项的数据库上下文:
枚举context.ContactPreferences DbSet 导致将它们从数据库中提取到DbContext缓存中。当您稍后检索联系人时,EF“修复”首选项导航属性,以便它包含已经获取的ContactPreference对象。见https://docs.microsoft.com/en-us/ef/core/querying/tracking
除非您提出要求,否则不会加载相关实体。以下是如何申请:https://docs.microsoft.com/en-us/ef/core/querying/related-data
答案 1 :(得分:0)
您在某处有ContactPreferences
成员,与yourContact.Preferences
不同。如果yourContact.ContactPreferences
是yourContact.Preferences
的成员,则需要使用ContactPreferences
而不是Contact
。