gpt4 book ai didi

entity-framework-4.1 - HasRequired 和 HasOptional 有什么区别

转载 作者:行者123 更新时间:2023-12-04 02:15:58 26 4
gpt4 key购买 nike

我有以下实体

public class SchoolContext : DbContext
{
public DbSet<Address> Addresses { get; set; }
public DbSet<Employee> Employees { get; set; }
}

public class Address
{
public int Id { get; set; }
public string Street { get; set; }

public virtual Employee Employee { get; set; }
}

public class Employee
{
public int Id { get; set; }
public string Name { get; set; }

public virtual Address Address { get; set; }
}

如果我使用以下 Fluent API 设置 Employee 和 Address 之间的关系
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
// Option #1
modelBuilder.Entity<Employee>()
.HasRequired(s => s.Address)
.WithRequiredPrincipal(a => a.Employee);

// Option #2
modelBuilder.Entity<Employee>()
.HasOptional(s => s.Address)
.WithRequired(a => a.Employee);

}

以上两个选项创建的表结构完全相同,如果是这样,两个选项之间有什么不同。如果我选择选项 #1,我认为 Employee 实体总是应该有地址实体,但事实并非如此。我能够在没有地址值的情况下保存 Employee 实体。

提前致谢。

最佳答案

仅根据 HasRequired 和 HasOptional 的含义,我希望 Optional #1 强制执行地址,并且不允许您在不指定地址的情况下创建员工,而选项 #2 确实允许您创建具有可选地址的员工。

HasRequired
Configures a required relationship from this entity type. Instances of the entity type will not be able to be saved to the database unless this relationship is specified. The foreign key in the database will be non-nullable.

HasOptional
Configures an optional relationship from this entity type. Instances of the entity type will be able to be saved to the database without this relationship being specified. The foreign key in the database will be nullable.

http://msdn.microsoft.com/en-us/library/gg671317%28v=vs.103%29.aspx
http://msdn.microsoft.com/en-us/library/gg671230%28v=vs.103%29.aspx

关于entity-framework-4.1 - HasRequired 和 HasOptional 有什么区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7430619/

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