我希望有人能够帮助我解决问题。
我首先使用实体框架代码,但我正在努力处理外键关系。
关系是这样建立的:
public class ExpScen
{
[Key]
[DisplayName("Exposure Id")]
public int ExpId { get; set; }
[DisplayName("Request Id")]
[Required(ErrorMessage = "Request Id is required")]
public int ReqId { get; set; }
[DisplayName("Quantity")]
[MaxLength(50, ErrorMessage = "The maximum length for Quantity is 50 characters")]
public string Quantity { get; set; }
[DisplayName("No. Exposed")]
[MaxLength(1, ErrorMessage = "The maximum length for No. Exposed is 1 character")]
public string Number { get; set; }
[DisplayName("Categories")]
public string Categories { get; set; }
[DisplayName("Others")]
public string Others { get; set; }
[DisplayName("Why Exposed")]
public string WhyExposed { get; set; }
public virtual ICollection<ActScen> ActScens { get; set; }
}
public class ActScen
{
[Key]
[ForeignKey("ExpScen")]
[DisplayName("Exposure Id")]
public int? ExpId { get; set; }
[DisplayName("Activity No")]
public string ActNo { get; set; }
[DisplayName("Method")]
public string Method { get; set; }
[DisplayName("Area")]
public string Area { get; set; }
[DisplayName("Exposure")]
public string Exposure { get; set; }
public ExpScen ExpScen { get; set; }
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
modelBuilder.Entity<ExpScen>().HasOptional(e => e.ActScens);
}
一个 ExpScen 可以有 0 到多个 ActScen。如果我对 ExpScen 进行简单查询: return _context.ExpScens.Where(r => r.ReqId == reqId).ToList();
ActScens 作为 null 返回,当我检查对象时可以看到这些错误:
{"Unable to cast object of type 'Infrastructure.Models.ActScen' to type 'System.Collections.Generic.ICollection`1[Infrastructure.Models.ActScen]'."}
{"Unable to set field/property ActScens on entity type System.Data.Entity.DynamicProxies.ExpScen_83F73B45A46F6AC263EB586EA84603C8228AF8B2673F23BF020CAC9C52BE4FE3. See InnerException for details."}
有人知道我在哪里出错了吗?谢谢