[英]ef core ignore navigation property
我有一个实体User
,它有两个属性CreatedBy
和UpdatedBy
都引用User
。 默认情况下,EF假定这两者是彼此一对一的关系。 我收到以下错误消息:
消息:System.InvalidOperationException:无法确定在“User.CreatedBy”和“User.UpdatedBy”之间检测到的一对一关系的子/依赖方。 要标识关系的子/依赖方,请配置外键属性。 如果这些导航不应该是相同关系的一部分,则在不指定反向的情况下配置它们。 有关详细信息,请参阅http://go.microsoft.com/fwlink/?LinkId=724062 。
目前,我有一个这样的类:
public class User
{
public int Id { get; set; }
public int? CreatedById { get; set; }
public User CreatedBy { get; set; }
public int? UpdatedById { get; set; }
public User UpdatedBy { get; set; }
}
基本上,这是我正在尝试的:
CreatedBy
并且任意数量的用户都可以拥有相同的UpdatedBy
。 如何让EF忽略导航属性? 我有CreatedBy
是我以后可以使用Include(u => u.CreatedBy)
。 我知道使用IEnumerable<User> AllCreatedUsers
属性可以解决这个问题,但我不想为我的实体中的每一个创建一个IEnumerable
。 有没有办法用流畅的API做到这一点?
这是我尝试过的:
modelBuilder.Entity<User>()
.Property<IEnumerable<User>>("AllCreatedUsers");
modelBuilder.Entity<User>().HasOne(u => u.CreatedBy)
.WithMany(u => EF.Property<IEnumerable<User>>(u, "AllCreatedUsers"));
您需要使用无参数WithMany
方法重载来配置两个单导航属性关系:
modelBuilder.Entity<User>()
.HasOne(u => u.CreatedBy)
.WithMany();
modelBuilder.Entity<User>()
.HasOne(u => u.UpdatedBy)
.WithMany();
您对两个属性的ForeignKey
数据注释。
public class User
{
public int Id { get; set; }
public int? CreatedById { get; set; }
[ForeignKey("CreatedById")]
public User CreatedBy { get; set; }
public int? UpdatedById { get; set; }
[ForeignKey("UpdatedById")]
public User UpdatedBy { get; set; }
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.