Multiply relationships ef core

asp.net-core c# entity-framework-core

Question

I'm using entity core 3. I have 2 classes User and Ticket. User may have many Ticket's to me and many Ticket's from me. Ticket should have User-sender and 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'. Either manually configure the relationship, or ignore this property using the '[NotMapped]' attribute or by using 'EntityTypeBuilder.Ignore' in 'OnModelCreating'.

Do you have any ideas?:)

1
0
2/26/2020 7:38:35 AM

Accepted Answer

You can use one of these

1 - Metadata. you can use InverseProperty to define the relationships.

if you use the metadata you should set UserToId and UserFromId to 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

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); 
}
2
2/26/2020 9:19:42 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow