[英]Multiply relationships ef core
I'm using entity core 3. I have 2 classes User
and Ticket
.我正在使用实体核心 3。我有 2 个类
User
和Ticket
。 User
may have many Ticket
's to me and many Ticket
's from me. User
可能有很多Ticket
的,我和很多Ticket
我送给。 Ticket
should have User
-sender and User
-receiver. Ticket
应该有User
-sender 和User
-receiver。 I did so:我这样做了:
public class User
{
public int Id { get; set; }
public string PasswordHash { get; set; }
public string Email { get;
public ICollection<Ticket> TicketsToMe { get; set; }
public ICollection<Ticket> TicketsFromMe { get; set; }
}
public class Ticket
{
public int Id { get; set; }
public string Title { get; set; }
public int UserToId { get; set; }
public int UserFromId { get; set; }
public User UserTo { get; set; }
public User UserFrom { get; set; }
}
And I got the error: Unable to determine the relationship represented by navigation property 'Ticket.UserTo' of type 'User'.我得到了错误:无法确定由“用户”类型的导航属性“Ticket.UserTo”表示的关系。 Either manually configure the relationship, or ignore this property using the '[NotMapped]' attribute or by using 'EntityTypeBuilder.Ignore' in 'OnModelCreating'.
手动配置关系,或使用“[NotMapped]”属性或使用“OnModelCreating”中的“EntityTypeBuilder.Ignore”忽略此属性。
Do you have any ideas?:)你有什么想法?:)
You can use one of these您可以使用其中之一
1 - Metadata. 1 - 元数据。 you can use
InverseProperty
to define the relationships.您可以使用
InverseProperty
来定义关系。
if you use the metadata you should set
UserToId
andUserFromId
toNullable
如果您使用元数据,您应该将
UserToId
和UserFromId
设置为Nullable
public class User
{
public int Id { get; set; }
public string PasswordHash { get; set; }
public string Email { get; set; }
[InverseProperty("UserTo")]
public ICollection<Ticket> TicketsToMe { get; set; }
[InverseProperty("UserFrom")]
public ICollection<Ticket> TicketsFromMe { get; set; }
}
2 - FluentApi 2 - FluentApi
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<User>()
.HasMany(a => a.TicketsFromMe)
.WithOne(a => a.UserFrom)
.HasForeignKey(a => a.UserFromId).OnDelete(DeleteBehavior.Restrict);
modelBuilder.Entity<User>()
.HasMany(a => a.TicketsToMe)
.WithOne(a => a.UserTo)
.HasForeignKey(a => a.UserToId).OnDelete(DeleteBehavior.Restrict);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.