WithRequiredPrincipal, why still have to define Required or ForeignKey to be able to compile? - entity-framework

public class Admin : EntityTypeConfiguration<Admin>
{
//[ForeignKey("Blog")] -- If I enable this, it compiles
public int AdminId { get; set; }
public string AdminName { get; set; }
public string AdminPicture { get; set; }
//[Required] -- Or If I enable this, it compiles
public virtual Blog Blog { get; set; }
}
public class Blog : EntityTypeConfiguration<Blog>
{
public int BlogId { get; set; }
public string BlogName { get; set; }
public string BlogUrl { get; set; }
public virtual Admin Admin { get; set; }
public Blog()
{
HasRequired(a => a.Admin).WithRequiredPrincipal(b=>b.Blog);
}
}
As long as I am defining HasRequired and WithRequiredPrincipal keys, why VS still creates below error.
Unable to determine the principal end of an association between the types 'Dummy.Models.Blog' and 'Dummy.Models.Admin'. The principal end of this association must be explicitly configured using either the relationship fluent API or data annotations.
Second thing is, even I enable [Required] or [ForeingKey] attr., in edmx designer, I only see 1 - 0..1 But I must see 1 - 1 (both end required)

1-1 relationship is not possible at database level, because you can't insert two rows at the same time. 1-1 is only possible at class validation level.
To make a 1-1 relationship, the primary key of the dependant entity must be the foreign key of the principal entity; that's the only way to make a 1-1 relationship. So, you have to make the following changes (considering that you are using EF Code First):
public class Admin
{
public int AdminId { get; set; }
public string AdminName { get; set; }
public string AdminPicture { get; set; }
public virtual Blog Blog { get; set; }
}
Blog should not have its own BlogId, because a blog belongs to an admin, and the admin can have only one blog (1-1 relationship). If you create a BlogId, with an AdminId FK, you would be making a 1-n relationship. Furthermore, do not mix the entity class with the mapping class, they should be different things. See the example below:
public class Blog
{
public int AdminId { get; set; } //PK AND FK
public string BlogName { get; set; }
public string BlogUrl { get; set; }
public virtual Admin Admin { get; set; }
}
Creating the relationship with a mapping class:
public class BlogMapping : EntityTypeConfiguration<Blog>
{
public BlogMapping()
{
HasKey(i => i.AdminId);
HasRequired(a => a.Admin)
.WithRequiredDependent(i => i.Blog);
}
}
Register the mapping inside the dbContext class:
public class MyDbContext : DbContext
{
public DbSet<Admin> Admins { get; set; }
public DbSet<Blog> Blogs { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Configurations.Add(new BlogMapping());
}
}
This will generate the following migration:
CreateTable(
"dbo.Admins",
c => new
{
AdminId = c.Int(nullable: false, identity: true),
AdminName = c.String(),
AdminPicture = c.String(),
})
.PrimaryKey(t => t.AdminId);
CreateTable(
"dbo.Blogs",
c => new
{
AdminId = c.Int(nullable: false),
BlogName = c.String(),
BlogUrl = c.String(),
})
.PrimaryKey(t => t.AdminId)
.ForeignKey("dbo.Admins", t => t.AdminId)
.Index(t => t.AdminId);
Hope this helps!

Related

Defining Self Referencing Foreign-Key-Relationship Using Entity Framework 7 Code First

I have an ArticleComment entity as you can see below:
public class ArticleComment
{
public int ArticleCommentId { get; set; }
public int? ArticleCommentParentId { get; set; }
//[ForeignKey("ArticleCommentParentId")]
public virtual ArticleComment Comment { get; set; }
public DateTime ArticleDateCreated { get; set; }
public string ArticleCommentName { get; set; }
public string ArticleCommentEmail { get; set; }
public string ArticleCommentWebSite { get; set; }
public string AricleCommentBody { get; set; }
//[ForeignKey("UserIDfk")]
public virtual ApplicationUser ApplicationUser { get; set; }
public Guid? UserIDfk { get; set; }
public int ArticleIDfk { get; set; }
//[ForeignKey("ArticleIDfk")]
public virtual Article Article { get; set; }
}
I want to define a foreign key relationship in such a way that one comment can have many reply or child, I've tried to create the relationship using fluent API like this:
builder.Entity<ArticleComment>()
.HasOne(p => p.Comment)
.WithMany()
.HasForeignKey(p => p.ArticleCommentParentId)
.OnDelete(DeleteBehavior.Restrict)
.IsRequired(false);
I followed the solution that was proposed here and here, but I get an error with the message:
Introducing FOREIGN KEY constraint 'FK_ArticleComment_ArticleComment_ArticleCommentParentId' on table 'ArticleComment' 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.
First I though by setting the OnDelete(DeleteBehavior.Restrict) this would go away, but the problem persist, also I've tried to use the data annotation [ForeignKey("ArticleCommentParentId")] as you can see the commented code in the ArticleComment definition, but it didn't work, I'd appreciate any though on this.
You are not modeling correctly your entity. Each comment needs a Set of replies, which are of type ArticleComment too, and each of those replies are the ones that point back to its parent (Note the added ICollection Replies property):
public class ArticleComment
{
public ArticleComment()
{
Replies = new HashSet<ArticleComment>();
}
public int ArticleCommentId { get; set; }
public int? ParentArticleCommentId { get; set; }
public virtual ArticleComment ParentArticleComment{ get; set; }
public virtual ICollection<ArticleComment> Replies { get; set; }
//The rest of the properties omitted for clarity...
}
...and the fluent Mapping:
modelBuilder.Entity<ArticleComment>(entity =>
{
entity
.HasMany(e => e.Replies )
.WithOne(e => e.ParentArticleComment) //Each comment from Replies points back to its parent
.HasForeignKey(e => e.ParentArticleCommentId );
});
With the above setup you get an open-ended tree structure.
EDIT:
Using attributes you just need to decorate ParentArticleComment property.
Take into account that in this case EF will resolve all the relations by convention.
[ForeignKey("ParentArticleCommentId")]
public virtual ArticleComment ParentArticleComment{ get; set; }
For collection properties EF is intelligent enough to understand the relation.
I simplified the class (removing foreign key support fields) and it works.
It could be an issue of your EF version (I've just installed it but actually I think I'm using rc1 but I'm not sure because I had several dependency issues) or it could be your model.
Anyway, this source works fine
public class ArticleComment
{
public int ArticleCommentId { get; set; }
public virtual ArticleComment Comment { get; set; }
public DateTime ArticleDateCreated { get; set; }
public string ArticleCommentName { get; set; }
public string ArticleCommentEmail { get; set; }
public string ArticleCommentWebSite { get; set; }
public string AricleCommentBody { get; set; }
}
class Context : DbContext
{
public Context(DbContextOptions dbContextOptions) : base(dbContextOptions)
{}
public DbSet<ArticleComment> Comments { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<ArticleComment>()
.HasOne(p => p.Comment)
.WithMany();
}
}
static class SampleData
{
public static void Initialize(Context context)
{
if (!context.Comments.Any())
{
var comment1 = new ArticleComment()
{
AricleCommentBody = "Article 1"
};
var comment2 = new ArticleComment()
{
AricleCommentBody = "Article 2 that referes to 1",
Comment = comment1
};
context.Comments.Add(comment2);
context.Comments.Add(comment1);
context.SaveChanges();
}
}
}

creating 1-1 relationship between two class using code first and migration

Well, it is 1st time i am trying to create 1-1 relationship between two tables using code first. I took some help online and come across the following classes mapping.
Than I ran migration and found something wrong. E.g. The migration says that primary key for StudentDetails is Id from Student table whereas I am looking to have primary key StudentId. Also, the foreign key is being created in opposite way.
Please can someone highlight what is wrong here or is it me who perceived it wrong.
I need to use Id from student class as Foreign key in StudentDetails class.
public class Student
{
public bool isPass{get;set;}
public virtual StudentReport Report { get; set; }
}
public class StudentReport
{
[Key, ForeignKey("Student")]
public Guid Id { get; set; }
public Guid? StudentReportId { get; set; }
public string RollNumber { get; set; }
public string StudentType { get; set; }
public virtual Student Student { get; set; }
}
When i run my migration, i get the following outcome which looks not good.
public partial class StudentReport : DbMigration
{
public override void Up()
{
CreateTable(
"dbo.StudentReport",
c => new
{
Id = c.Guid(nullable: false, identity: true),
StudentReportId = c.Guid(),
RollNumber = c.String(),
StudentType = c.String(),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.Student", t => t.Id)
.Index(t => t.Id);
}
In an one to one relationship one end must be the principal and the another one is the dependent. If you are going to declare a FK property in the dependent entity, EF requires that property should be PK too:
public class Principal
{
[Key]
public int Id{get;set;}
public virtual Dependent Dependent{get;set;}
}
public class Dependent
{
[Key, ForeignKey("Principal")]
public int PrincipalId{get;set;}
public virtual Principal Principal{get;set;}
}
If you want to have both entities with their own PKs, and also use Id from Student entity as FK in StudentReport class, then you can try with this model:
public class Student
{
[Key]
public Guid Id { get; set; }
public bool isPass{get;set;}
}
public class StudentReport
{
[Key]
public Guid StudentReportId{ get; set; }
[ForeignKey("Student")]
public Guid StudentId { get; set; }
public string RollNumber { get; set; }
public string StudentType { get; set; }
public virtual Student Student { get; set; }
}
I guess what you really need is an one to many relationship because an student could have 0 or many reports.
Check this link. It could help you understand better how to use the FK properties and the name conventions that have by default Code First.
Update 1
If you want to create an one to one relationship and both entities have their owns PKs, then you can't define a FK property in the dependent entity due to the restriction I explain at the begin of my answer. A solution for what you need could be using the Required attribute and deleting the FK property:
public class Student
{
[Key]
public Guid Id { get; set; }
public bool isPass{get;set;}
public virtual StudentReport StudentReport { get; set; }
}
public class StudentReport
{
[Key]
public Guid StudentReportId{ get; set; }
public string RollNumber { get; set; }
public string StudentType { get; set; }
[Required]
public virtual Student Student { get; set; }
}
Update 2
Are you sure? The migration code that I get is this:
AddForeignKey("dbo.StudentReports", "StudentReportId", "dbo.Students", "Id");
Which is not ok yet because Code First is still configuring by convention the PK of StudentReport as FK. To avoid that you can add this Fluent Api configuration to your context:
modelBuilder.Entity<StudentReport>()
.HasRequired(sr => sr.Student)
.WithOptional(s => s.StudentReport)
.Map(c=>c.MapKey("Student_Id"));
This way Code First will generate this migration code:
AddColumn("dbo.StudentReports", "Student_Id", c => c.Guid(nullable: false));
CreateIndex("dbo.StudentReports", "Student_Id");
AddForeignKey("dbo.StudentReports", "Student_Id", "dbo.Students", "Id");

Add an entity to your initial migration

I am using code first migrations in an asp.net mvc program.
I am using the default authenticion and roles which is provided in the project.
Now when I enabled migrations it automatically generated a migration class which generates all of the tables etc.
Here is an excample of the specific table which I wqish to edit.
CreateTable(
"dbo.AspNetUserRoles",
c => new
{
UserId = c.String(nullable: false, maxLength: 128),
RoleId = c.String(nullable: false, maxLength: 128),
})
.PrimaryKey(t => new { t.UserId, t.RoleId })
.ForeignKey("dbo.AspNetRoles", t => t.RoleId, cascadeDelete: true)
.ForeignKey("dbo.AspNetUsers", t => t.UserId, cascadeDelete: true)
.Index(t => t.RoleId)
.Index(t => t.UserId);
Now I would like to add a description field to this table. It would be really easy if i just added it in the database but then I will loose my code first migrations.
1> Where does Entity framework get all its commands for the initial migration? Because there are no models in my project that I can see which specify the tables it creates.
2> How can I modify or edit some of the original tables which are generated? I have tried just editing the initial migrations folder but that does not work?
(Just my thinking) Is it not that maybe the Roles and users models are stored in the framework and that is where it gets the structure of the tables from? If so Can i not extend the default model to add more attributes? Cause I know you can do it for the ApplicationUser, I have done so before, here is an example of it:
// You can add profile data for the user by adding more properties to your ApplicationUser class, please visit http://go.microsoft.com/fwlink/?LinkID=317594 to learn more.
public class ApplicationUser : IdentityUser
{
[Required]
[MaxLength(50)]
[Display(Name = "Email Address")]
public string email { get; set; }
}
Thats how i can add a email address field to the default user. Can I not maybe do this with the roles as well.
You dit it perfectly for the ApplicationUser, just continue like that for the other stuff. If you want to add description to the table of the users. Just add it to the ApplicationUser model. Don't mind the foreign keys and virtual properties.
public class ApplicationUser : IdentityUser
{
[Required]
public string FirstName { get; set; }
[Required]
public string LastName { get; set; }
public string GroupName { get; set; }
[Required]
public string Email { get; set; }
[Required]
[StringLength(15)]
public string Phone { get; set; }
public string Remark { get; set; }
public DateTime? BirthDate { get; set; }
public DateTime ValidFrom { get; set; }
public DateTime ValidUntil { get; set; }
// Foreign keys
[ForeignKey("Bank")]
public string AccountNumber { get; set; }
[ForeignKey("Address")]
public int? AddressId { get; set; }
public virtual Bank Bank { get; set; }
public virtual Address Address { get; set; }
public virtual ICollection<Request> Requests { get; set; }
}
For editing the role class, you should inherit IdentityRole on your class and add the properties:
public class ApplicationRole : IdentityRole
{
public string Description { get; set; }
}
The framework will generate new migration classes which will be ran when you use the Update-Database command.
You have to change your identityManager (Use ApplicationRole here):
public class IdentityManager
{
public bool RoleExists(string name)
{
var rm = new RoleManager<ApplicationRole>(new RoleStore<ApplicationRole>(new ApplicationDbContext()));
return rm.RoleExists(name);
}
public bool CreateRole(string name)
{
var rm = new RoleManager<ApplicationRole>(new RoleStore<ApplicationRole>(new ApplicationDbContext()));
var idResult = rm.Create(new ApplicationRole(name));
return idResult.Succeeded;
}
}
You have to overwrite the Role in ApplicationDbContext doing like following (don't forget the new):
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext()
: base("DefaultConnection")
{
}
...
public DbSet<Product> Products { get; set; }
new public DbSet<ApplicationRole> Roles { get; set; }
}

MVC EF code first creating model class

I'm new to MVC and EF code first. I'm in struggle to model a real-estate company DB model using EF code-first approach and I did some exercises as well as reading some online tutorials.
First thing I have a customers table that would be in relation with one or more properties he/she has registered as it's owner to sell or to rent, I was wondering if it is possible to have some sub classes inside a model class for registered properties as below:
public Property
{
public int PropertyID { get; set; }
public bool IsforSale { get; set; }
public bool IsforRent { get; set; }
public class Apartment{
public int ApartmentID { get; set; }
public int AptSqureMeter { get; set; }
. . .
. . .
}
public class Villa{
public int VillaID { get; set; }
public int VillaSqureMeter { get; set; }
. . .
. . .
}
and also other sub-classes for other types of properties
}
If the answer is Yes, then how should I declare the relations using data annotation or Fluent API, and then please help me how to update both Customers table and Property table with the customer information and property info at the same time?
thanks for your answer in advance.
As #Esteban already provided you with a pretty detailed answer on how to design your POCOs and manage the relationship between them, I will only focus on that part of your question:
how should I declare the relations using data annotation or Fluent API
First of all, you should know that certain model configurations can only be done using the fluent API, here's a non exhaustive list:
The precision of a DateTime property
The precision and scale of numeric properties
A String or Binary property as fixed-length
A String property as non-unicode
The on-delete behavior of relationships
Advanced mapping strategies
That said, I'm not telling you to use Fluent API instead of Data Annotation :-)
As you seem to work on an MVC application, you should keep in mind that Data Annotation attributes will be understood and processed by both by Entity Framework and by MVC for validation purposes. But MVC won't understand the Fluent API configuration!
Both your Villa and Apartment classes have similar properties, if they are the same but as it's type, you could create an enum for that.
public enum PropertyType {
Apartment = 1,
Villa
}
public class Property {
public int PropertyID { get; set; }
public bool IsforSale { get; set; }
public bool IsforRent { get; set; }
public PropertyType PropertyType { get; set; }
public int SquareMeter { get; set; }
}
This way of modelating objects is refered as plain old clr object or POCO for short.
Assume this model:
public class User {
public int UserId { get; set; }
public string Username { get; set; }
public virtual List<Role> Roles { get; set; }
}
public class Role {
public int RoleId { get; set; }
public string Name { get; set; }
public virtual List<User> Users { get; set; }
}
Creating relations with fluent api:
Mapping many to many
On your OnModelCreating method (you'll get this virtual method when deriving from DbContext):
protected override void OnModelCreating(DbModelBuilder builder) {
// Map models/table
builder.Entity<User>().ToTable("Users");
builder.Entity<Role>().ToTable("Roles");
// Map properties/columns
builder.Entity<User>().Property(q => q.UserId).HasColumnName("UserId");
builder.Entity<User>().Property(q => q.Username).HasColumnName("Username");
builder.Entity<Role>().Property(q => q.RoleId).HasColumnName("RoleId");
builder.Entity<Role>().Property(q => q.Name).HasColumnName("Name");
// Map primary keys
builder.Entity<User>().HasKey(q => q.UserId);
builder.Entity<Role>().HasKey(q => q.RoleId);
// Map foreign keys/navigation properties
// in this case is a many to many relationship
modelBuilder.Entity<User>()
.HasMany(q => q.Roles)
.WithMany(q => q.Users)
.Map(
q => {
q.ToTable("UserRoles");
q.MapLeftKey("UserId");
q.MapRightKey("RoleId");
});
Mapping different types of relationships with fluent api:
One to zero or one:
Given this model:
public class MenuItem {
public int MenuItemId { get; set; }
public string Name { get; set; }
public int? ParentMenuItemId { get; set; }
public MenuItem ParentMenuItem { get; set; }
}
And you want to express this relationship, you could do this inside your OnModelCreating method:
builder.Entity<MenuItem>()
.HasOptional(q => q.ParentMenuItem)
.WithMany()
.HasForeignKey(q => q.ParentMenuItemId);
One to many
Given this model:
public class Country {
public int CountryId { get; set; }
public string Name { get; set; }
public virtual List<Province> Provinces { get; set; }
}
public class Province {
public int ProvinceId { get; set; }
public string Name { get; set; }
public int CountryId { get; set; }
public Country Country { get; set; }
}
You now might want to express this almost obvious relationship. You could to as follows:
builder.Entity<Province>()
.HasRequired(q => q.Country)
.WithMany(q => q.Provinces)
.HasForeignKey(q => q.CountryId);
Here are two useful links from MSDN for further info:
Configuring Relationships with the Fluent API.
Code First Relationships Fluent API.
EDIT:
I forgot to mention how to create a many to many relationship with additional properties, in this case EF will NOT handle the creation of the join table.
Given this model:
public class User {
public int UserId { get; set; }
public string Username { get; set; }
public virtual List<Role> Roles { get; set; }
pubilc virtual List<UserEmail> UserEmails { get; set; }
}
pubilc class Email {
public int EmailId { get; set; }
public string Address { get; set; }
public List<UserEmail> UserEmails { get; set; }
}
public class UserEmail {
public int UserId { get; set; }
public int EmailId { get; set; }
public bool IsPrimary { get; set; }
public User User { get; set; }
public Email Email { get; set; }
}
Now that we've added a new property into our join table ef will not handle this new table.
We can achieve this using the fluent api in this case:
builder.Entity<UserEmail>()
.HasKey( q => new {
q.UserId, q.EmailId
});
builder.Entity<UserEmail>()
.HasRequired(q => q.User)
.WithMany(q => q.UserEmails)
.HasForeignKey(q => q.EmailId);
builder.Entity<UserEmail>()
.HasRequired(q => q.Email)
.WithMany(q => q.UserEmails)
.HasForeignKey(q => q.UserId);

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