我正在尝试创建2个实体,用户和用户评论,其中用户评论具有复合主键,这些键是用户的ID,被审核的人以及执行此操作的人,此复合主键也是用户表中主键的外键,但EF正在创建一个额外的列,我没有看到它的重点,当我向数据库保存一个User Review对象时,该列没有被填充,它始终是空。
这导致当我尝试检索具有评论的用户时,评论集合始终为空,除非 User_SubjectId 列包含用户的ID。
我的查询就像这样
return _context.Users
.Include(u => u.Reviews)
.Where(u => u.SubjectId.Equals(subjectId));
评论集合始终为空
用户评论实体
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace API.Data.Entities
{
public class UserReview
{
[Key, Column(Order = 0), ForeignKey("Reviewer")]
public string ReviewerId { get; set; } //The user that wrote the review
[Key, Column(Order = 1), ForeignKey("ReviewedUser")]
public string ReviewedUserId { get; set; } //The user who was reviewed
[Required]
[Range(1, 5)]
public int Rating { get; set; }
[Required]
public DateTimeOffset DateCreated { get; set; }
[Required]
public virtual User Reviewer { get; set; }
[Required]
public virtual User ReviewedUser { get; set; }
}
}
用户实体就像这样
public class User
{
[Key]
[Required]
public string SubjectId { get; set; }
public User()
{
Reviews = new List<UserReview>();
}
public virtual ICollection<UserReview> Reviews { get; set; }
}
但是,当我添加迁移时,我的UserReviews表中会创建另一列,如此图所示,该列为 User_SubjectId
我不知道这是EF中的错误还是我的映射错误,无论如何都有任何想法?
由于
答案 0 :(得分:1)
您必须使用ReverseProperty注释。
public class UserReview
{
[Key, Column(Order = 0), ForeignKey("Reviewer")]
public string ReviewerId { get; set; } //The user that wrote the review
[Key, Column(Order = 1), ForeignKey("ReviewedUser")]
public string ReviewedUserId { get; set; } //The user who was reviewed
[Required]
[Range(1, 5)]
public int Rating { get; set; }
[Required]
public DateTimeOffset DateCreated { get; set; }
[Required]
public virtual User Reviewer { get; set; }
[Required)]
public virtual User ReviewedUser { get; set; }
}
public class User
{
[Key]
[Required]
public string SubjectId { get; set; }
public User()
{
Reviews = new List<UserReview>();
}
[InverseProperty("ReviewedUser")] // or Reviewer.
public virtual ICollection<UserReview> Reviews { get; set; }
}
在我看来,这是使用流畅映射时更易于配置的事情。