Navigation Properties using two foreign keys - entity-framework

I have a project with several tables in the same database.
public class UserImage
{
[Key]
public int Id { get; set; }
public string OwnerId { get; set; }
[ForeignKey("OwnerId")]
public virtual ApplicationUser Owner { get; set; }
//some fields are removed for brevity
}
public class FriendRequest
{
[Key]
public int Id { get; set; }
public string UserId { get; set; }
public string FutureFriendUserId { get; set; }
[ForeignKey("UserId")]
public virtual ApplicationUser User { get; set; }
[ForeignKey("FutureFriendUserId")]
public virtual ApplicationUser FutureFriendUser { get; set; }
}
public class ApplicationUser : IdentityUser
{
//some fields are removed for brevity
public virtual ICollection<UserImage> UserImages { get; set; }
public virtual ICollection<FriendRequest> FriendRequests { get; set; }
The problem is that I can find the images that belong to a user:
var userStore = new UserStore<ApplicationUser>(db);
var userManager = new UserManager<ApplicationUser>(userStore);
ApplicationUser user = userManager.FindById(User.Identity.GetUserId());
IEnumerable<string> imgs = (from image in user.UserImages select Url.Content(image.ImageUrl)).Skip(skip).Take(5).ToList();
but I can't use the same technique for the FriendRequests. If I search in the database for the rows that have UserId == User.Identity.GetUserId() or some other id, the results are what I expect.
What is the problem?

What you're essentially creating here is a self-referential many-to-many relationship. On your FriendRequest class, you have two properties that are foreign keys to ApplicationUser, but on your ApplicationUser class, you have only a single collection of FriendRequest. Entity Framework has no idea which foreign key should actually compose this collection. As a result, you have to make a few changes to get this working properly.
You must add another navigation property. Essentially, on your ApplicationUser class you'll end up with something like the following:
public virtual ICollection<FriendRequest> SentFriendRequests { get; set; }
public virtual ICollection<FriendRequest> ReceivedFriendRequests { get; set; }
Again, you need a collection for each foreign key.
You'll need to add some fluent config to help Entity Framework determine which foreign key to use for each collection:
public class ApplicationContext : DbContext
{
...
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<FriendRequest>().HasRequired(m => m.User).WithMany(m => m.SentFriendRequests);
modelBuilder.Entity<FriendRequest>().HasRequired(m => m.FutureFriendUser).WithMany(m => m.ReceivedFriendRequests);
}

Related

Link models from different databases

I have the following situation: I have a class Company, it is as simple as possible
public class Company
{
public int ID { get; set; }
public string Name { get; set; }
}
I also need to extend the IdentityUser class from ASP. NET Identity Core:
public class User : IdentityUser
{
public Company Company { get; set; }
public int CompanyID { get; set; }
}
Not bad so far. But I also need a class Device :
public class Device
{
public Company Company { get; set; }
public int CompanyID { get; set; }
}
Accordingly, we add the Devices property of the List<Device> type to the Company class and Users property of the List<User> type.
The problem is that I want to separate the data (Device table) from the data of ASP .NET Identity Core in different databases. Table Company I want to put in the database with Auth data. And table Device in other one. How can I tell the Entity Framework that the Company property of the Device class is from another database?
If the Company property is from another database, you may need to add a second database context for it, if you haven't already. Something like this:
public class CompanyModelContext : DbContext
{
public CompanyModelContext(DbContextOptions options) : base(options){ }
public DbSet<Company> Company { get; set; }
}
You can try to set your EF model like this:
Companies table:
[Table("Companies")]
public class Company
{
[Key]
public int ID { get; set; }
public string Name { get; set; }
public ICollection<Device> Devices { get; set; }
}
Devices table:
[Table("Devices")]
public class Device
{
[Key]
public int Id { get; set; }
public Company Company { get; set; }
public int CompanyID { get; set; }
}
ApplicationDbContext class:
public DbSet<Company> Companies { get; set; }
public DbSet<Device> Devices { get; set; }
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
builder.Entity<Company>(buildAction =>
{
buildAction.ToTable("Companies");
buildAction.HasMany(x => x.Devices)
.WithOne(x => x.Company)
.OnDelete(DeleteBehavior.Cascade);
};
}
I've added Devices as a list in Company class, then overriding the FK in the method OnModelCreating.
Once you delete an item in table Company, all items with the same Id in table Devices (comparing to CompanyID) will be delted automatically.
Since we use the 2 properties [Table] and [Key] to define table name and the primary key. So in the OnModelCreating, you can ignore to define the name, PK, FK of table Device.
Company has many User
In this case:
User class:
public class User : IdentityUser
{
public int CompanyId { get; set; }
public Company Company { get; set; }
}
Company class:
[Table("Companies")]
public class Company
{
[Key]
public int ID { get; set; }
public string Name { get; set; }
public ICollection<Device> Devices { get; set; }
public ICollection<User> Users { get; set; }
}
ApplicationDbContext class:
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
builder.Entity<Company>(buildAction =>
{
buildAction.ToTable("Companies");
buildAction.HasMany(x => x.Devices)
.WithOne(x => x.Company)
.OnDelete(DeleteBehavior.Cascade);
buildAction.HasMany(x => x.Users)
.WithOne(x => x.Company)
.OnDelete(DeleteBehavior.Cascade);
};
}

How can I name a navigation property a different name from it's entity name in my EF POCO?

I have a POCO Entity named Employee.
And then I have a second POCO Entity named Case.
I want a navigation property that looks like instead this:
public class Case : BaseEntity
{
public long EmployeeId { get; set; }
public virtual Employee Employee{ get; set; }
like this:
public class Case : BaseEntity
{
public long InitialContactId { get; set; }
public virtual Employee InitialContact { get; set; }
I want to name my property InitialContact. Not Employee.
But I get this error when EF tries to create the Database:
Unable to determine the relationship represented by navigation property 'Case.InitialContact' of type 'Employee'. Either manually configure the relationship, or ignore this property from the model.
Update 1:
I got it to work like this:
public class Case : BaseEntity
{
public long InitialContactId { get; set; }
[ForeignKey("Id")]
public virtual Employee InitialContact { get; set; }
public DateTime InitalConsultDate { get; set; }
public Guid AppUserId { get; set; }
public virtual AppUser LerSpecialist { get; set; }
}
The primary key is ID in my BaseEntity. Not EmployeeId.
But I have second part to my question.
Here is my Complete Employee POCO:
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using Hrsa.Core.Generic.Model.Framework.Concrete;
using Microsoft.AspNetCore.Mvc.ModelBinding;
namespace Hrsa.Core.Generic.Model.Lerd
{
public class Employee : BaseEntity
{
[BindNever]
public string Email { get; set; }
[BindNever]
public long OrganizationId { get; set; }
[BindNever]
public string Supervisor { get; set; }
[BindNever]
public string SupervisorEmail { get; set; }
[BindNever]
public string FirstName { get; set; }
[BindNever]
public string LastName { get; set; }
public string Notes { get; set; }
[BindNever]
public long BargainingUnitId { get; set; }
[BindNever]
public long PayPlanId { get; set; }
[BindNever]
public long GradeRankId { get; set; }
[BindNever]
public long PositionTitleId { get; set; }
[BindNever]
public long SeriesId { get; set; }
public bool IsUnionEmployee { get; set; }
public virtual Organization Organization { get; set; }
public virtual BargainingUnit BargainingUnit { get; set; }
public virtual PayPlan PayPlan { get; set; }
public virtual GradeRank GradeRank { get; set; }
public virtual PositionTitle PositionTitle { get; set; }
public virtual Series Series { get; set; }
public virtual ICollection<UnionHours> UnionHours { get; set; }
public virtual ICollection<Case> Cases { get; set; }
[NotMapped]
public string UnionEmployeeYesNo => (IsUnionEmployee) ? "Yes" : "No";
}
}
I want my Employee to have many Cases:
public virtual ICollection<Case> Cases { get; set; }
Here is my complete Cases POCO:
public class Case : BaseEntity
{
public long InitialContactId { get; set; }
[ForeignKey("Id")]
public virtual Employee InitialContact { get; set; }
public DateTime InitalConsultDate { get; set; }
public Guid AppUserId { get; set; }
public virtual AppUser LerSpecialist { get; set; }
}
So now my DB looks like this:
So I have my InitialContactId in Cases ok.
But now I need my Case to have many Employees.
So I add this in to my Case POCO:
public virtual ICollection<Employee> Employees { get; set; }
Now it looks like this:
public class Case : BaseEntity
{
public long InitialContactId { get; set; }
[ForeignKey("Id")]
public virtual Employee InitialContact { get; set; }
public DateTime InitalConsultDate { get; set; }
public Guid AppUserId { get; set; }
public virtual AppUser LerSpecialist { get; set; }
public virtual ICollection<Employee> Employees { get; set; }
}
Now when I run it, I get this error again:
Unable to determine the relationship represented by navigation property 'Case.InitialContact' of type 'Employee'. Either manually configure the relationship, or ignore this property from the model.
Update 2:
I found this article for a Many-Many relationship in .Net Core 1:
http://www.learnentityframeworkcore.com/configuration/many-to-many-relationship-configuration
So now I have a bridge lookup entity:
public class EmployeeCase
{
[ForeignKey("Id")]
public long EmployeeId { get; set; }
public Employee Employee { get; set; }
[ForeignKey("Id")]
public long CaseId { get; set; }
public Case Case { get; set; }
}
Employee POCO:
Changed:
public virtual ICollection<Case> Cases { get; set; }
to:
// Mapping - Collection of Cases
public virtual ICollection<EmployeeCase> EmployeeCases { get; set; }
Case POCO:
Changed:
public virtual ICollection<Employee> Employees { get; set; }
to:
// Mapping - Collection of Employees
public virtual ICollection<EmployeeCase> EmployeeCases { get; set; }
In my AppDbContext
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
#region Many-to-Many Employees Cases
modelBuilder.Entity<EmployeeCase>()
.HasKey(ec => new { ec.EmployeeId, ec.CaseId });
modelBuilder.Entity<EmployeeCase>()
.HasOne(ec => ec.Employee)
.WithMany(e => e.EmployeeCases)
.HasForeignKey(ec => ec.EmployeeId);
modelBuilder.Entity<EmployeeCase>()
.HasOne(ec => ec.Case)
.WithMany(c => c.EmployeeCases)
.HasForeignKey(ec => ec.CaseId);
#endregion
}
Now when I run I get this error:
An exception of type 'System.Data.SqlClient.SqlException' occurred in Microsoft.EntityFrameworkCore.Relational.dll but was not handled in user code
Additional information: Introducing FOREIGN KEY constraint 'FK_EmployeeCase_Employees_EmployeeId' on table 'EmployeeCase' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints.
Could not create constraint or index. See previous errors.
Update 3:
Finally got my tables the way I want with this piece of code from:
Introducing FOREIGN KEY constraint may cause cycles or multiple cascade paths - why?
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
// Get rid of Cascading Circular error on ModelBuilding
foreach (var relationShip in modelBuilder.Model.GetEntityTypes().SelectMany(e => e.GetForeignKeys()))
{
relationShip.DeleteBehavior = DeleteBehavior.Restrict;
}
#region Many-to-Many Employees Cases
modelBuilder.Entity<EmployeeCase>()
.HasKey(ec => new { ec.EmployeeId, ec.CaseId });
modelBuilder.Entity<EmployeeCase>()
.HasOne(ec => ec.Employee)
.WithMany(e => e.EmployeeCases)
.HasForeignKey(ec => ec.EmployeeId);
modelBuilder.Entity<EmployeeCase>()
.HasOne(ec => ec.Case)
.WithMany(c => c.EmployeeCases)
.HasForeignKey(ec => ec.CaseId);
#endregion
base.OnModelCreating(modelBuilder);
}
Update 4:
This did not work after all.
Remvoving the delete behavior for everything messes up my other relationships and I get errors.
How can I fix this?
This is disgusting.
So wishing I did not go Core.
Entity Framework uses conventions to guess how to map your C# model to database objects.
In your case you violate convention by custom name, so you should explain Entity Framework how to map this stuff.
There are two possible ways: attributes and fluent API. I'd suggest to use the latter one.
See section "Configuring a Foreign Key Name That Does Not Follow the Code First Convention" here: Entity Framework Fluent API - Relationships
I have made it a habit of explicitly defining my relationships as EF does not always get them the way I want. I like to create a Mapping folder that contains my entity maps. The fluent api works great for this and inherits from EntityTypeConfiguration.
Try this.
public class CaseMap : EntityTypeConfiguration<Case>
{
public CaseMap()
{
HasKey(m => m.Id)
HasRequired(m => m.InitialContact)
.WithMany(e => e.Cases)
.HasForeignKey(m => m.InitialContactId);
}
}
Almost forgot. You need to tell your DbContext where to find these mappings. Add this to your DbContexts OnModelCreating method.
modelBuilder.Configurations.AddFromAssembly(typeof(MyContext).Assembly);
This is what worked finally for the Cascading Delete circular references on the many-to-many in EF Core:
// Get rid of Cascading Delete Circular references error.
var type = modelBuilder.Model.GetEntityTypes().Single(t => t.Name == "Hrsa.Core.Generic.Model.Lerd.EmployeeCase");
foreach (var relationship in type.GetForeignKeys())
{
relationship.DeleteBehavior = DeleteBehavior.Restrict;
}
You have to get the Entity representing the many to many lookup only.
And from there restrict the DeleteBehavior.

how to configure cascade delete with EF Fluent API

I have the following classes and EF convention created the tables fine - all good. Now I want to configure cascade delete on the ToDoList (so that when I delete a ToDoList, all the ToDoItems and UserToDoLists also gets deleted automatically). Must I re-specify what EF convention is able to detect in order to set WillCascadeOnDelete? How do I specify this relationship in fluent API?
public class ToDoList
{
public int Id { get; set; }
public string Description { get; set; }
public virtual ICollection<ToDoItem> ToDoItems { get; set; }
public virtual ICollection<UserToDoList> UserToDoLists { get; set; }
}
public class ApplicationUser : IdentityUser
{
public ApplicationUser()
: base()
{
}
public virtual ICollection<UserToDoList> UserToDoLists { get; set; }
}
// a todolist can have many users and a user can have many todolist
// junction table will have addition fields
public class UserToDoList
{
public string UserId { get; set; }
public virtual ApplicationUser User { get; set; }
public virtual int ToDoListId { get; set; }
public virtual ToDoList ToDoList { get; set; }
// additional fields
public bool IsOwner { get; set; }
public int Ordinal { get; set; }
public bool AllowEdit { get; set; }
}
public class UserToDoListConfig : EntityTypeConfiguration<UserToDoList>
{
public UserToDoListConfig()
{
HasKey(ut => new { ut.UserId, ut.ToDoListId });
}
}
public class ToDoListConfig : EntityTypeConfiguration<ToDoList>
{
public ToDoListConfig()
{
Property(t => t.Description).IsRequired().HasMaxLength(50);
HasMany(t =>t.UserToDoLists).??
}
}
That's a simple one-to-many relationship from ToDoList to your junction table UserToDoList, so you just have to set up the mapping like this
HasMany(m => m.UserToDoLists)
.WithRequired(m => m.ToDoList)
.HasForeignKey(m => m.ToDoListId);
and EF will handle your cascading deletes automatically, because ToDoList is required on the junction table side.

EntityType 'CustomUserLogin' has no key defined. Define the key for this EntityType

I've just started a new project in Web Forms because I thought it'd be quicker than learning MVC, but how wrong was I! I'm struggling with the Identity aspect of my project. I've followed this link here: http://www.asp.net/identity/overview/extensibility/change-primary-key-for-users-in-aspnet-identity
And it all compiles ok and works (my ID column is now an integer).
So I've created a new class for a 'Property' context:
using System.Collections.Generic;
using System.Data.Entity;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.AspNet.Identity.EntityFramework;
using System.Web.Security;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.ModelConfiguration.Conventions;
namespace MyApp.Models
{
public class PropertyContext : DbContext
{
public PropertyContext()
: base("DefaultConnection")
{
}
public DbSet<Property> Property { get; set; }
}
public class Property
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity), ScaffoldColumn(false)]
public int PropertyID { get; set; }
//[Required, StringLength(128)]
//public string OwnerID { get; set; }
// [ForeignKey("OwnerID")]
//public virtual ApplicationUser ApplicationUser { get; set; }
//[ForeignKey("OwnerID")]
//public int OwnerID { get; set; }
// public virtual ApplicationUser ApplicationUser { get; set; }
public int OwnerID { get; set; }
[ForeignKey("OwnerID")]
public virtual ApplicationUser ID { get; set; }
[Required, StringLength(255), Display(Name = "Address 1")]
public string Address1 { get; set; }
[Required, StringLength(255), Display(Name = "Address 2")]
public string Address2 { get; set; }
[Required, StringLength(255), Display(Name = "Address 3")]
public string Address3 { get; set; }
[Required, StringLength(255), Display(Name = "Town/City")]
public string Settlement { get; set; }
[Required, StringLength(255), Display(Name = "County")]
public string County { get; set; }
[Required, StringLength(255), Display(Name = "Post Code")]
public string PostCode { get; set; }
[Required, StringLength(255), Display(Name = "Country")]
public string Country { get; set; }
}
}
Whereby I'm trying to make a new int column called 'OwnerID' a foreign key into the 'AspNetUser' table's ID column. When i build my project, it builds fine. However when I try to add a migration I get this:
MyApp.Models.CustomUserLogin: : EntityType 'CustomUserLogin' has no key defined. Define the key for this EntityType.
MyApp.Models.CustomUserRole: : EntityType 'CustomUserRole' has no key defined. Define the key for this EntityType.
CustomUserLogins: EntityType: EntitySet 'CustomUserLogins' is based on type 'CustomUserLogin' that has no keys defined.
CustomUserRoles: EntityType: EntitySet 'CustomUserRoles' is based on type 'CustomUserRole' that has no keys defined.
So in my ApplicationDbContext I've added this:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<ApplicationUser>().ToTable("Users").HasKey<int>(u => u.Id);
modelBuilder.Entity<CustomUserRole>().ToTable("UserRoles").HasKey(ur => new { ur.RoleId, ur.UserId });
modelBuilder.Entity<CustomUserLogin>().ToTable("UserLogins").HasKey<int>(ul => ul.UserId);
modelBuilder.Entity<CustomUserClaim>().ToTable("UserClaims").HasKey<int>(uc => uc.Id);
modelBuilder.Entity<CustomRole>().ToTable("Roles").HasKey<int>(r => r.Id);
}
and even this
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<CustomUserLogin>().HasKey(cul => cul.UserId);
modelBuilder.Entity<CustomUserRole>().HasKey(cur => cur.UserId);
But it still doesn't work. And to be quite honest I'm burning up a whole weekend by stabbing in the dark. I can't believe something as simple as creating a foreign key is so difficult in this Entity Framework environment.
Can anybody give me a pointer? Thanks.
I did exactly as you did.
Added Identity to my MVC Web Application
Changed the primary key to be an INT rather a GUID
Added an EmployeeProfile and a CustomerProfile to the ApplicationUser
I did not have to override OnModelCreating as I made my own changes to the database tables to support what I needed.
Added two new properties to the ApplicationUser class in IdentityModels.cs
public virtual CustomerProfile CustomerProfile { get; set; }
public virtual EmployeeProfile EmployeeProfile { get; set; }
I created the CustomerProfile and EmployeeProfile classes. Note the Data Annotations on the Id property of each class. The Id property is the ForeignKey property to guide the virtual User property back to the ApplicationUser.
public class EmployeeProfile
{
[Key, ForeignKey("User")]
public int Id { get; set; }
public DateTime HireDate { get; set; }
public DateTime BirthDate{ get; set; }
public virtual ApplicationUser User { get; set; }
}
public class CustomerProfile
{
[Key, ForeignKey("User")]
public int Id { get; set; }
public CustomerType CustomerType { get; set; }
public string Company { get; set; }
public string Address { get; set; }
public string City { get; set; }
public string State { get; set; }
public string ZipCode { get; set; }
public string WorkPhone { get; set; }
public string CustomerId { get; set; }
public string AccountType { get; set; }
public virtual ApplicationUser User { get; set; }
}
In my ApplicationDbContext class, I added the following lines of code:
public DbSet<CustomerProfile> CustomerProfile { get; set; }
public DbSet<EmployeeProfile> EmployeeProfile { get; set; }
Everything was working as expected. I logged in and saw the Customer and Employee info in my views.
I started seeing the error you received "EntityType 'CustomUserLogin' has no key defined. Define the key for this EntityType" when I added a many to many relation ship in the EmployeeProfile class to a Departments class. In my scenario an Employee can belong to 1 or many departments and a department can have many employees. My database changes were good and even the classes compiled just like you experienced, however once I ran the project, the website would error out.
Backing out my changes resolved the issue. Something in my classes was throwing off the validation of the model, so I'll need to approach the problem differently. So just like in my case, your poco classes may have an issue.
Remove your 'Property' class and references. Make the project work with the base essentials. Once you have it working, add the Property class back in with just the Id property.
Let me know if you still need help.
Place the base.OnModelCreating at the bottom:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
modelBuilder.Entity<ApplicationUser>().ToTable("Users").HasKey<int>(u => u.Id);
modelBuilder.Entity<CustomUserRole>().ToTable("UserRoles").HasKey(ur => new { ur.RoleId, ur.UserId });
modelBuilder.Entity<CustomUserLogin>().ToTable("UserLogins").HasKey<int>(ul => ul.UserId);
modelBuilder.Entity<CustomUserClaim>().ToTable("UserClaims").HasKey<int>(uc => uc.Id);
modelBuilder.Entity<CustomRole>().ToTable("Roles").HasKey<int>(r => r.Id);
base.OnModelCreating(modelBuilder);
}

M:M Mapping - EF 4.3 CodeFirst (Existing Database)

I have two tables (Table A, Table B) joined with a join table (TableAB) with 3 payload columns. By Payload I mean columns apart from Id, TableAId, and TableBId.
I can insert into all tables successfully, but I need to insert data into one of the payload columns on Insert. I'm using EF 4.3, Fluent API. Can anyone help? Thanks in advance.
public class Organisation : EntityBase<int>, IAggregateRoot
{
public string Name { get; set; }
public string Url { get; set; }
public int CountryId { get; set; }
public int? OwnershipTypeId { get; set; }
public int OrganisationStatusId { get; set; }
public virtual ICollection<Feature> Features { get; set; }
public virtual ICollection<OrganisationType> OrganisationTypes { get; set; }
public virtual ICollection<PricePlan> PricePlans { get; set; }
public virtual ICollection<User> Users { get; set; }
}
public class User: EntityBase<Guid>, IAggregateRoot
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string JobTitle { get; set; }
public int? PhoneCallingCodeId { get; set; }
public int? PhoneAreaCode{ get; set; }
public string PhoneLocal { get; set; }
public int? MobileCallingCodeId { get; set; }
public int? MobileAreaCode { get; set; }
public string MobileLocal { get; set; }
public virtual ICollection<Organisation.Organisation> Organisations { get; set; }
}
public class OrganisationUser : EntityBase<int>, IAggregateRoot
{
public DateTime StartDate { get; set; }
public DateTime? EndDate { get; set; }
public int OrganisationRoleId {get; set;}//Foreign Key - have tried leaving it out, tried it as public virtual Organisation Organisation {get;set;
public bool IsApproved { get; set; }
}
public class SDContext : DbContext
{
public ObjectContext Core
{
get
{
return (this as IObjectContextAdapter).ObjectContext;
}
}
public IDbSet<User> User { get; set; }
public IDbSet<Organisation> Organisation { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
modelBuilder.Entity<Organisation>().HasMany(u => u.Users).WithMany(o => o.Organisations).Map(m =>
{
m.MapLeftKey("OrganisationId");
m.MapRightKey("UserId");
m.ToTable("OrganisationUser");
});
//I have tried specifically defining the foreign key in fluent, but I really need to understand how I can add the payload properties once I access and edit them.
Your mapping is not correct for your purpose. If you want to treat OrganisationUser as an intermediate entity between Organisation and User you must create relationships between Organisation and OrganisationUser and between User and OrganisationUser, not directly between Organisation and User.
Because of the intermediate entity which contains its own scalar properties you cannot create a many-to-many mapping. EF does not support many-to-many relationships with "payload". You need two one-to-many relationships:
public class Organisation : EntityBase<int>, IAggregateRoot
{
// ...
// this replaces the Users collection
public virtual ICollection<OrganisationUser> OrganisationUsers { get; set; }
}
public class User : EntityBase<Guid>, IAggregateRoot
{
// ...
// this replaces the Organisations collection
public virtual ICollection<OrganisationUser> OrganisationUsers { get; set; }
}
public class OrganisationUser : EntityBase<int>, IAggregateRoot
{
public int OrganisationId { get; set; }
public Organisation Organisation { get; set; }
public Guid UserId { get; set; }
public User User { get; set; }
// ... "payload" properties ...
}
In Fluent API you must replace the many-to-many mapping by the following:
modelBuilder.Entity<Organisation>()
.HasMany(o => o.OrganisationUsers)
.WithRequired(ou => ou.Organisation)
.HasForeignKey(ou => ou.OrganisationId);
modelBuilder.Entity<User>()
.HasMany(u => u.OrganisationUsers)
.WithRequired(ou => ou.User)
.HasForeignKey(ou => ou.UserId);
Your derived DbContext may also contain a separate set for the OrganisationUser entity:
public IDbSet<OrganisationUser> OrganisationUsers { get; set; }
It's obvious now how you write something into the intermediate table:
var newOrganisationUser = new OrganisastionUser
{
OrganisationId = 5,
UserId = 8,
SomePayLoadProperty = someValue,
// ...
};
context.OrganisastionUsers.Add(newOrganisastionUser);
context.SaveChanges();
If you want to make sure that each pair of OrganisationId and UserId can only exist once in the link table, it would be better to make a composite primary key of those two columns to ensure uniqueness in the database instead of using a separate Id. In Fluent API it would be:
modelBuilder.Entity<OrganisationUser>()
.HasKey(ou => new { ou.OrganisationId, ou.UserId });
More details about such a type of model and how to work with it is here:
Create code first, many to many, with additional fields in association table