gpt4 book ai didi

entity-framework - 如何使用 EF CTP5 保存 ICollection

转载 作者:行者123 更新时间:2023-12-04 07:23:12 25 4
gpt4 key购买 nike

我的类(class)有以下属性:团队

[Key]
public virtual long Id { get; set; }

public Guid ClubIdentifier { get; set; }
public GenderEnum Gender { get; set; }
public TeamAgeCategoryEnum TeamAgeCategory { get; set; }
public ICollection<int> BirthYears { get; set; }

如何将属性 BirthYears 中的内容保存到我的数据库中,我让 EF 基于模型创建我的数据库,但我的数据库中遗漏了属性 BirthYears。我本来希望有一个包含 int 值和我的 Team Id 值的新表。

我错过了什么,我想我需要在我的存储库类中做一些 OnModelCreating 方法。

最佳答案

如果你看看 EntityTypeConfiguration<TEntityType>在类中,您将看到以下用于定义一对多关系的签名(这是您在 TeamBirthYears 之间的关系):

HasMany<TTargetEntity>(Expression<Func<TEntityType, ICollection<TTargetEntity>>>
navigationPropertyExpression) where TTargetEntity : class;

如您所见,有一个约束 where TTargetEntity : class这需要 BirthYearsclass的合集对象。 int不是一个类,所以映射是不可能的。

我能看到的唯一解决方法是定义一个小类......
public class BirthYear
{
public int Id { get; set; }
public int Value { get; set; }
}

...然后在您的 Team 类集合中使用它:
public ICollection<BirthYear> BirthYears { get; set; }

映射约定应自动创建一对多关系,这样您就不需要 Fluent API 来设置关联。

编辑

根据拉迪斯拉夫在评论中的正确评论者的更正:

类(class) BirthYear需要一个额外的 Key 属性。我添加了一个属性 Id .

我也猜 BirthYears将是依赖于 Team 的属性.映射约定将从 BirthYear 创建可选关系。至 Team .我认为通过使用 Fluent API 使模型需要这种关系会更适合:
modelBuilder.Entity<Team>()
.HasMany(t => t.BirthYears)
.WithRequired();

这将自动启用级联删除 - 删除团队时将从数据库中删除关联的出生年。

编辑 2

(再次基于 Ladislav 的评论)如果您不想复制 BirthYears 表中的年份,您还可以设置多对多关系:
modelBuilder.Entity<Team>()
.HasMany(t => t.BirthYears)
.WithMany();

这将在 TeamBirthYears 之间添加一个连接表( Team )和 BirthYear进入数据库。从存储空间或性能的角度来看,您可能不会赢得任何东西(因为 BirthYear 类非常小,而且 BirthYear 表中的记录与连接表中的记录具有相同的大小)。但如果您想扩展 BirthYear,这可能是一个更好的方法。迟早会通过其他属性来分类。否则我个人会保持简单的一对多关系。但选择权在你。

关于entity-framework - 如何使用 EF CTP5 保存 ICollection<int>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5566454/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com