0

所以我有3门课:

public class OwnerDto
{
    public int Id { get; set; }

    public string Name { get; set; }

    public string EmailAddress { get; set; }
}

public class SitterDto
{
    public int Id { get; set; }

    public string Name { get; set; }

    public string EmailAddress { get; set; }
}

public class ReviewDto
{
    public int Id { get; set; }

    public int Rating { get; set; }

    //[ForeignKey("OwnerId")]
    public OwnerDto Owner { get; set; }

    //[ForeignKey("SitterId")]
    public SitterDto Sitter { get; set; }
}

但我不知道如何做正确的模型构建器。我尝试的一切都失败了:(我正在学习,所以请耐心等待。

我最接近的尝试是这样的:

           modelBuilder.Entity<ReviewDto>()
                    .HasOne(t => t.Owner).WithMany().HasForeignKey("OwnerId");

基本上 Owner 和 Sitter 总是 null :( 我应该保留 [ForeignKey()] 的东西还是应该使用不同的扩展方法?

4

2 回答 2

0

该场景需要参考Eager Loading,可以使用该Include方法指定查询结果中包含的相关数据。

var query = from review in context.Review.Include(o => o.Owner).Include(s=>s.Sitter) select review;
于 2018-08-06T06:35:04.353 回答
0

相互声明所有具有导航属性的类。ForeignKey用其主键上的属性标记其中一个表(从属表) 。

EF 从中推断出一对多:

public class OwnerDto
{
    public int Id { get; set; }

    public string Name { get; set; }

    public string EmailAddress { get; set; }

    public ICollection<ReviewDto> Reviewers{ get; set; }

    public ICollection<SitterDto> Sitters{ get; set; }

}

public class SitterDto
{
    public int Id { get; set; }

    public string Name { get; set; }

    public string EmailAddress { get; set; }

    public int OwnerId{ get; set; }
    [ForeignKey("OwnerId")]
    public OwnerDto Owner { get; set; }
}

public class ReviewDto
{
    public int Id { get; set; }

    public int Rating { get; set; }


    public int OwnerId{ get; set; }
    [ForeignKey("OwnerId")]
    public OwnerDto Owner { get; set; }

}

并且 EF 从中一对一地推断:

public class OwnerDto
{
    ...

    public ReviewDto Review{ get; set; }
    ...
}
public class ReviewDto
{

   [ForeignKey("Owner")]
   public int OwnerId { get; set; }
   public OwnerDto Owner{ get; set; }
   ...

}
于 2018-08-06T05:38:38.483 回答