我正在使用Fluent API创建一对一或零关系,在第一种情况下 经理-ContactDetails起作用,但在第二种情况下,代表-ContactDetails则不起作用。但是配置是相同的。
据我了解,在一对一/零关系中,两个类之一应将键定义为primary和foreignKey,以便知道哪个类是依赖的。例如,ContactDetails中的ID不能同时作为代表表和管理器表的外键吗?这就是为什么会自动创建Representative_Id的原因?但是为什么这种关系被认为是一对多的呢?
经理班级:
[Table("Manager")]
public class Manager
{
[Key]
[ForeignKey("ApplicationUser")]
public string Id { get; set; }
[Required]
[MaxLength(100)]
public string Name { get; set; }
public virtual ContactDetail ContactDetail { get; set; }
[JsonIgnore]
public virtual ICollection<Client> Clients { get; set; }
public virtual ApplicationUser ApplicationUser { get; set; }
}
代表班:
[Table("Representative")]
public class Representative
{
[Key]
public int Id { get; set; }
[Required]
[MaxLength(99)]
public string Name { get; set; }
[Required]
public int ClientId { get; set; }
[JsonIgnore]
public virtual Client Client{ get; set; }
public virtual ContactDetail ContactDetail {get; set; }
}
ContactDetail类:
public class ContactDetail
{
[Key]
public string Id { get; set; }
[Required]
[MaxLength(100)]
public string FirstName { get; set; }
[MaxLength(100)]
public string SecondName { get; set; }
[MaxLength(100)]
public string LastName { get; set; }
[JsonIgnore]
public virtual Manager Manager { get; set; }
[JsonIgnore]
public virtual Representative Representative { get; set; }
}
覆盖上下文的方法:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Manager>()
.HasOptional(m => m.ContactDetail)
.WithRequired(ad => ad.Manager);
modelBuilder.Entity<Representative>()
.HasOptional(c => c.ContactDetail)
.WithRequired(ad => ad.Representative);
base.OnModelCreating(modelBuilder);
}