实体框架在循环集合中返回NULL

时间:2016-02-13 16:08:46

标签: c# sql .net sql-server entity-framework

我有一个我从未见过的奇怪问题。实体框架在导航属性集合中返回NULL对象。当我查看它时,我以循环方式访问它。您可以在集合和NULL对象上看到下面的屏幕截图。我也给出了下面的路径。任何线索为什么会发生这种情况?

我抓住了这个,因为AutoMapper不喜欢它。

`"Missing type map configuration or unsupported mapping.\n\nMapping types:\r\nDivision -> DivisionModel\r\nTournaments.Data.Entities.Division -> Tournaments.Models.Divisions.DivisionModel\n\nDestination path:\nList`1[0].Event.Divisions.Divisions1[1]\n\nSource value:\nTournaments.Data.Entities.Division"`

实体路径

DivisionBracket -> Division - Event -> List<Divisions> (has NULL and original Division)

Division.cs

[Table("Division", Schema = "")]
    public class Division : BaseEntity
    {
        public int EventId { get; set; }

        [ForeignKey("EventId")]
        public Event Event { get; set; }

Event.cs

[Table("Event", Schema = "")]
    public class Event : BaseEntity
    {
        [InverseProperty("Event")]
        public virtual ICollection<Division> Divisions { get; set; }

映射

modelBuilder.Entity<Division>() .HasRequired(a => a.Event) .WithMany() .HasForeignKey(u => u.EventId).WillCascadeOnDelete(true);

enter image description here

1 个答案:

答案 0 :(得分:3)

我认为该部门有mising映射配置。可能你需要在DivisionMap.cs上添加关系映射(1到N映射)

对于前

导致此错误

this.HasOptional(a =&gt; a.Occupation)。 WithMany() .HasForeignKey(c =&gt; c.OccupationId);

正确的方式

this.HasOptional(a =&gt; a.Occupation)。 WithMany(x =&gt; x.Employee) .HasForeignKey(c =&gt; c.OccupationId);