Optional One-to-many Relationship in Entity Framework

前端 未结 3 931
有刺的猬
有刺的猬 2021-01-18 14:25

I\'m having issues getting an optional one-to-many relationship to work.

My model is:

public class Person
{
    public int Identifier { get; set; }
          


        
相关标签:
3条回答
  • 2021-01-18 14:39

    You can try this:

    this.HasOptional(s => s.Department)
        .WithMany(s => s.Members)
        .HasForeignKey(s => s.MemberOfDepartment);
    
    0 讨论(0)
  • 2021-01-18 14:40
    modelBuilder.Entity<Department>().HasMany(x => x.MemberOfDepartment).WithOptional();
    
    0 讨论(0)
  • 2021-01-18 14:44

    Also try this:

    public class Person
    {
        public int Identifier { get; set; }
        public int DepartmentIdentifier {get; set;}
        public virtual Department Department { get; set; }
    }
    
    public class Department
    {
        public int Identifier { get; set; }
    
        public virtual IList<Person> Members { get; set; }
    }
    

    EF Person config using Fluent API:

    this.HasRequired(p => p.Department).WithMany(d => d.Members).HasForeignKey(p => 
    p.DepartmentIdentifier);
    
    this.Property(p => p.DepartmentIdentifier).IsRequired();
    
    0 讨论(0)
提交回复
热议问题