0
我似乎无法弄清楚为什么我的导航属性不能通过我的include语句构建。EF 6:包含不构建导航属性
这里是我的方法:
public async Task<IHttpActionResult> GetCompanies(string id)
{
DbContext.Database.Log = s => System.Diagnostics.Debug.WriteLine(s);
var company = await DbContext.Companies.Where(x => x.Id.ToString() == id).Include(x => x.StartelAccounts).FirstOrDefaultAsync();
if (company != null)
{
return Ok(this.TheModelFactory.Create(company));
}
return NotFound();
}
当我测试从调试日志中我得到的所有字段和值两个对象的SQL。
下面是型号:
public class CompanyGroup
{
[Key]
public Guid Id { get; set; }
[Required]
[MaxLength(100)]
public string Name { get; set; }
[Required]
[DataType(DataType.Date)]
public DateTime FirstBillingDate { get; set; }
[Required]
public int TermLength { get; set; }
public virtual ICollection<ApplicationUser> Members { get; set; }
public virtual ICollection<AccountStartel> StartelAccounts { get; set; }
public CompanyGroup()
{
Members = new HashSet<ApplicationUser>();
StartelAccounts = new HashSet<AccountStartel>();
}
}
public class AccountStartel
{
[Key]
public Guid Id { get; set; }
[Required]
public string ClientID { get; set; }
[Required]
public int DbId { get; set; }
[Required]
public string Name { get; set; }
[Required]
public string TimeZone { get; set; }
[Required]
public string AccountNum { get; set; }
public Guid CompanyId { get; set; }
public virtual CompanyGroup Company { get; set; }
public virtual ICollection<UsageReport> UsageReports { get; set; }
public AccountStartel()
{
Company = new CompanyGroup();
CompanyId = Guid.Empty;
UsageReports = new List<UsageReport>();
}
}
EF流利的API
modelBuilder.Entity<AccountStartel>()
.HasRequired<CompanyGroup>(x => x.Company)
.WithMany(x => x.StartelAccounts)
.HasForeignKey(x => x.CompanyId);
modelBuilder.Entity<AccountStartel>()
.Property(p => p.DbId)
.IsRequired()
.HasColumnAnnotation(
IndexAnnotation.AnnotationName,
new IndexAnnotation(
new System.ComponentModel.DataAnnotations.Schema.IndexAttribute("IX_StartelDbId", 1) { IsUnique = true }));
有人能看到我在想念着什么吗?
不相同的错误发生时,您使用DbContext.Companies.Where(X => x.Id.ToString()== ID).INCLUDE( x => x.StartelAccounts).FirstOrDefault()而不是等待异步?或者当你使导航属性非虚拟? – DevilSuichiro
删除等待异步并使该属性非虚拟时,我会得到相同的结果。没有例外,只是收集是空的。 – MrChrisOsburn
是否可以在AccountStartel构造函数中设置Company和/或CompanyId?如果你删除这些行,它会起作用吗? – Peter