【问题标题】:How to seed the database with a many-to-many relationship in Entity Code First如何在实体代码优先中使用多对多关系为数据库播种
【发布时间】:2012-12-07 22:01:06
【问题描述】:

我的代码中有一个多对多的关系,我正在尝试为数据库播种。这是我的种子方法:

var loc = new List<Location> {
      new Location { LocationName = "Paradise Lane" },
      new Location { LocationName = "81st Street" }
};
loc.ForEach(l => context.Locations.Add(l));


var soft = new List<Software> {
     new Software { Title = "Adobe Creative Suite", ... Locations = loc.Single(s => s.LocationName = "Paradise Lane")}
};
soft.ForEach(s => context.Software.Add(s));

这是我的位置类:

public class Location
    {
        public int Id { get; set; }
        [Required]
        [StringLength(20)]
        public string LocationName { get; set; }
        public virtual ICollection<Software> Software { get; set; }
    }

这是我的软件课:

public class Software
    {
        public int Id { get; set; }
        [Required]
        [StringLength(128)]
        public string Title { get; set; }
        [Required]
        [StringLength(10)]
        public string Version { get; set; }
        [Required]
        [StringLength(128)]
        public string SerialNumber { get; set; }
        [Required]
        [StringLength(3)]
        public string Platform { get; set; }
        [StringLength(1000)]
        public string Notes { get; set; }
        [Required]
        [StringLength(15)]
        public string PurchaseDate { get; set; }
        public bool Suite { get; set; }
        public string SubscriptionEndDate { get; set; }
        //[Required]
        //[StringLength(3)]
        public int SeatCount { get; set; }
        public virtual ICollection<Location> Locations { get; set; }
        public virtual ICollection<SoftwarePublisher> Publishers { get; set; }
        public virtual ICollection<SoftwareType> Types { get; set; }

    }

我收到两个错误。一,它告诉我我不能将字符串隐式转换为布尔值。我什至不知道我正在尝试这样做。第二,不能将 lambda express 转换为委托,因为块中的返回类型的 soem 不能隐式转换为委托返回类型。这是对 iCollection 的引用吗?

【问题讨论】:

    标签: c# asp.net-mvc-4 ef-code-first


    【解决方案1】:

    你错过了一个等号。用于比较的双等号。

    loc.Single(s => s.LocationName = "Paradise Lane")
    

    对比

    loc.Single(s => s.LocationName == "Paradise Lane")
    

    此外,您不能在 Locations 中使用 .Single(),因为它是 ICollectionSingle 返回 1 个对象,而不是集合。您应该改用 .Where 。或者您可以在其中隐式声明一个数组并在其中使用您的 .Single() 代码。

    编辑:同样显然 .Where() 不能很好地转换为 ICollection。添加一个 ToArray,你会得到一个可以接受的数组。

    【讨论】:

    • 所以你的意思是“loc.Where(s => s.LocationName == "Paradise Lane")”?编译器抱怨它需要强制转换。
    • 表示存在显式转换。那是类型位置列表吗?
    • 嗯。尝试将.ToArray() 添加到.Where() 的末尾。或者粘贴实际的错误文本,这样我就可以尝试解决了。
    • 错误 1 ​​无法将类型“System.Collections.Generic.IEnumerable”隐式转换为“System.Collections.Generic.ICollection”。存在显式转换(您是否缺少演员表?) D:\Websites\CIT\CIT\Models\SampleData.cs 21 248 CIT
    • 它使用 .ToArray(); 构建;
    猜你喜欢
    • 2013-05-02
    • 2021-11-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-26
    • 2011-07-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多