序列在实体框架代码优先迁移中包含多个元素错误

本文关键字:迁移 包含多 错误 元素 实体 框架 代码 | 更新日期: 2023-09-27 18:09:17

我创建了一些模型,添加了迁移,然后做了一个更新数据库操作,尽管在我最后一次更新数据库操作中,我得到了错误消息说:

序列包含多个元素

下面是我的迁移配置:

context.Restraunts.AddOrUpdate(r => r.name,
            new Restraunt { name = "farzi", city = "a", country = "b" },
             new Restraunt { name = "prime", city = "c", country = "d" },
              new Restraunt { name = "lord", city = "e", country = "f" },
              new Restraunt
              {
                  name = "barracks",
                  city = "g",
                  country = "h",
                  Reviews = new List<RestrauntReview>{
                      new RestrauntReview{rating=5,body="good food!",reviewername="vipul"}
              }

              });
        for (int i = 0; i < 1000; i++)
        {
            context.Restraunts.AddOrUpdate(r => r.name, new Restraunt { name = i.ToString(), city = "nowhere", country = "USA" });
        }
    }
}

你也可以在下面找到我的模型定义。

public class Restraunt
{
    public int Id { get; set; }
    public string name { get; set; }
    public string city { get; set; }
    public string country { get; set; }
    public virtual ICollection<RestrauntReview> Reviews { get; set; }
}

public class RestrauntReview : IValidatableObject
{
    public int id { get; set; } 
    [Required]
    [Range(1,10)]
    public int rating { get; set; } 
    [Required]
    [StringLength(1024)]
    public string body { get; set; }
    [Display(Name="USER NAME")]
    [DisplayFormat(NullDisplayText="ANONYMOUS")]
    public string reviewername { get; set; }
    public int RestrauntID { get; set; }
    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
    {
        if (rating < 2 && reviewername.ToLower().StartsWith("vipul"))
        {
            yield return new ValidationResult("sorry vipul... get out!!");
        }
    }
}

序列在实体框架代码优先迁移中包含多个元素错误

您必须在RestrauntReview模型上定义一个外键,如下所示。

    [ForeignKey("RestrauntID ")]
    public virtual Restraunt Restraunt { get; set; }
    public int RestrauntID { get; set; }