Add an entity to your initial migration - entity-framework

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; }
}

Related

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.

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

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!

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);
}

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");

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