Entity Framework - Inverse Property Relationships?

c# entity-framework entity-framework-core

Question

I'm having trouble understanding how I can accomplish the following relationships:

public class Organisation {

    public Guid Id { get; set; }

    // Have a single user as an administrator of a company
    public User AdminUser { get; set; }

    // All users associated with the company (including the admin)
    public ICollection<User> Users { get; set;}
}

public class User {

    public Guid Id { get; set; }

    // Each User must be associated with an Organisation.
    [ForeignKey("Organisation")]
    public Guid OrganisationId { get; set; }
    public Organisation Organisation { get; set; }
}

Is that something that can be done via Inverse Properties? I understand that they are a solution to define multiple relationships between the same entities, but I'm struggling to see how I can set this up for my situation. Could someone help out with example code?

Thanks in advance.

1
2
1/31/2018 7:43:27 PM

Popular Answer

In addition to attribute annotations, you can use fluent configurations. They are more powerful and flexible than the annotations, and allow you to configure multiple relationships between the same entities.

You can define the configurations in the OnModelCreating method in your DbContext class:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
   modelBuilder.Entity<Organisation>()
        .HasMany(o => o.Users)
        .WithOne(u => u.Organisation);

   modelBuilder.Entity<Organisation>()
        .HasOne(o => o.AdminUser)
        .WithOne(u => u.Organisation);
}

More info on fluent configurations: here. About one-to-many relationships: here. And about inverse navigation properties: here.

0
1/31/2018 9:24:45 PM


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