Entity framework .WithMany()和.WithOptional()之间的差异?

Entity framework .WithMany()和.WithOptional()之间的差异?,entity-framework,ef-code-first,fluent-interface,Entity Framework,Ef Code First,Fluent Interface,以下是两种类似的fluent API配置: WithMany() modelBuilder.Entity() .HasRequired(cou=>cou.Currency) .有很多 .WillCascadeOnDelete(假); WithOptional() modelBuilder.Entity() .HasRequired(cou=>cou.Currency) .WithOptional() .WillCascadeOnDelete(假); 我想在这里表达的是:每个国家都需要具体的货

以下是两种类似的fluent API配置:

WithMany()

modelBuilder.Entity()
.HasRequired(cou=>cou.Currency)
.有很多
.WillCascadeOnDelete(假);
WithOptional()

modelBuilder.Entity()
.HasRequired(cou=>cou.Currency)
.WithOptional()
.WillCascadeOnDelete(假);
我想在这里表达的是:每个
国家
都需要具体的
货币
,但是
货币
可以分配给零个、一个或多个国家


我必须使用上述哪种陈述?或者换句话说:
.WithMany()
.WithOptional()
操作符之间的区别是什么?

如果您的模型是这样的:

public class Country
{
    public int CountryId { get; set; }
    public Currency Currency { get; set; }
}

public class Currency
{
    public int CurrencyId { get; set; }
}
然后

modelBuilder.Entity<Country>()
            .HasRequired(cou => cou.Currency)
            .WithOptional()
            .WillCascadeOnDelete(false);
。。。在数据库的
国家
表中创建第二列
货币ID
,该列不可为空,是
货币
表的
货币ID
的外键。因此,
货币
记录可能没有相关的
国家
记录或一个或多个记录,因为外键现在是另一列,与主键不同。因此,
国家/地区
表中的多行可能具有相同的外键。这里的关系是
1对0…n

编辑

如果您为两种不同配置的型号使用以下代码

Country country1 = new Country();
Country country2 = new Country();
Currency currency = new Currency();

country1.Currency = currency;
country2.Currency = currency;

context.Countries.Add(country1);
context.Countries.Add(country2);

context.SaveChanges();
。。。然后第二种情况(.WithMany)起作用了:我们在数据库中得到了两个新国家和一种货币

然而有点奇怪的是,在第二种情况下(.has可选)只存储第一个国家,而忽略第二个国家。事实上,我本以为会有例外。我不确定这是否必须被视为一个bug

Edit2

将上面示例中的顺序更改为

context.Countries.Add(country1);
context.Countries.Add(country2);

country1.Currency = currency;
country2.Currency = currency;

。。。在“.HasOptional”案例中引发预期的异常。

啊,明白了。因此,.HasOptional()用于10 | 1,.HasMany()用于10 | n关系。伟大的这就是我想知道的。非常感谢@英格玛:看看我的编辑,也许值得知道。我刚刚发现,可能有一个与10 | 1关系有关的bug。您是指要引用的标题和说明。WithMany()和.WithOptional()而不是.HasMany()和.HasOptional()?我已经提交了一份编辑报告。
modelBuilder.Entity<Country>()
            .HasRequired(cou => cou.Currency)
            .WithMany()
            .WillCascadeOnDelete(false);
Country country1 = new Country();
Country country2 = new Country();
Currency currency = new Currency();

country1.Currency = currency;
country2.Currency = currency;

context.Countries.Add(country1);
context.Countries.Add(country2);

context.SaveChanges();
context.Countries.Add(country1);
context.Countries.Add(country2);

country1.Currency = currency;
country2.Currency = currency;