How to create a self referencing table using code first? - entity-framework

I have an entity that has a reference to itself in a parent - child relationship. I need to find out how to implement this using code first and fluent API. Below is my entity class.
public class MenuItem
{
public int Id { get; set; }
public string LinkText { get; set; }
public string ControllerName { get; set; }
public string ActionName { get; set; }
public MenuItem Parent { get; set; }
public int ParentId { get; set; }
private IList<Role> Roles;
private IList<MenuItem> ChildMenuItems;
public MenuItem()
{
Roles = new List<Role>();
ChildMenuItems = new List<MenuItem>();
}
}
I tried using the below code in my entity configuration.
HasOptional(m => m.Parent)
.WithMany(m => m.ChildMenuItems)
.HasForeignKey(m => m.ParentId)
.WillCascadeOnDelete(false);
but I got this error -
One or more validation errors were detected during model generation:
Vantage.Data.EF.MenuItem_Parent: : Multiplicity conflicts with the
referential constraint in Role 'MenuItem_Parent_Target' in
relationship 'MenuItem_Parent'. Because all of the properties in the
Dependent Role are non-nullable, multiplicity of the Principal Role
must be '1'.
All help appreciated.
Thank You.

ParentId field should be nullable. You are not able to create any record if parentid is required.
Just change public int ParentId { get; set; }
to public int? ParentId { get; set; }

Related

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

Entity Framework one-to-one relationship - Unable to determine the principal

I have 2 models:
public class TransactionHistory : IDbEntity {
[Key]
public int ID { get; set; }
public ItemHistory ItemHistory { get; set; }
}
public class ItemHistory : IDbEntity {
[Key]
public int ID { get; set; }
public int TransactionHistoryID { get; set; }
public TransactionHistory TransactionHistory { get; set; }
}
There's a one to one relationship between TransactionHistory and ItemHistory, ItemHistory MUST have a TransactionHistory but TransactionHistory may or may not have an ItemHistory.
I want to be able to do this in code:
var test = db.ItemHistory.Include(x => x.TransactionHistory).ToList();
As well as:
var test2 = db.TransactionHistory.Include(x => x.ItemHistory).ToList();
But I only want a single FK on the ItemHistory table.
With the code I've listed I get this error:
Unable to determine the principal end of an association between the types 'InventoryLibrary.DomainModels.TransactionHistory' and 'InventoryLibrary.DomainModels.ItemHistory'. The principal end of this association must be explicitly configured using either the relationship fluent API or data annotations.
How is this achieved in Entity Framework code first data annotations?
Firstly, you have to mark foreign keys by virtual keyword to enable overrides.
public class TransactionHistory : IDbEntity
{
[Key]
public int ID { get; set; }
public virtual ItemHistory ItemHistory { get; set; }
}
public class ItemHistory : IDbEntity
{
[Key]
public int ID { get; set; }
public int TransactionHistoryID { get; set; }
[Required]
public virtual TransactionHistory TransactionHistory { get; set; }
}
If HistoryItem must have Transaction History, add DataAnnotation [Required], which makes it non-nullable.
Finally, wonder, if you want to have one-to-one relationship. I imagine you'd like to have many transaction history entries. Am I right? If not - let me know.
To create one-to-many relationship, use IEnumerable<> type.

Entity Framework Code First relation in one table

I've a problem with creating a relation in one table. I have a UserProfile class. An another user can by only created by existing user. So I want to have fields with information about who created user and when the user was created. Maybe the code will say more :)
public class UserProfile
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int UserId { get; set; }
[Required, MaxLength(30)]
public string UserName { get; set; }
[Column(TypeName = "date")]
[Display(Name = "Data ważności")]
public DateTime ExpirationDate { get; set; }
[DataType(DataType.DateTime)]
[Display(Name = "Data dodania")]
[Column(TypeName = "datetime")]
public DateTime sysRegDate { get; set; }
[ForeignKey("sysRegUser")]
public int? sysRegUserId { get; set; }
[DataType(DataType.DateTime)]
[Column(TypeName = "datetime")]
public DateTime sysModDate { get; set; }
[ForeignKey("sysModUser")]
public int? sysModUserId { get; set; }
public virtual UserProfile sysRegUser { get; set; }
public virtual UserProfile sysModUser { get; set; }
}
But when I'm creating a migration I get error:
System.Data.Entity.ModelConfiguration.ModelValidationException: One or more validation errors were detected during model generation:
\tSystem.Data.Entity.Edm.EdmAssociationEnd: : Multiplicity is not valid in Role 'UserProfile_sysModUser_Source' in relationship 'UserProfile_sysModUser'. Because the Dependent Role properties are not the key properties, the upper bound of the multiplicity of the Dependent Role must be '*'.
Thanks in advance for answers.
I have used this code to create a parent-child relation, maybe it helps:
public class MyModel
{
public int Id {get;set;}
// ...
public int? ParentId {get;set;}
public virtual MyModel Parent {get;set;}
public virtual IList<MyModel> Children {get;set;}
}
And in the DbContext:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<MyModel>().HasOptional(p => p.Parent).WithMany(p => p.Children).HasForeignKey(p => p.ParentId);
modelBuilder.Entity<MyModel>().Property(p => p.ParentId).HasColumnName("Parent");
}

Entity Framework CF Fluent API mapping

I have 2 entities:
public class User
{
public int userId { get; set; }
public string name { get; set; }
public Guid userGuid { get; set; }
}
public class Absence
{
public int absenceId { get; set; }
public Guid applicantId { get; set; }
public User applicant { get; set; }
public Guid permitterId{ get; set; }
public User permitter{ get; set; }
...
}
AbsencesConfiguration:
this.HasRequired(u => u.Applicant).WithMany().HasForeignKey(d => d.ApplicantId);
this.HasRequired(u => u.Permitter).WithMany().HasForeignKey(d => d.PermitterId);
I'd like a Fluent API mapping between the two classes, but it gives this error message:
Blockquote\tSystem.Data.Entity.Edm.EdmAssociationConstraint: : The types of all properties in the Dependent Role of a referential constraint must be the same as the corresponding property types in the Principal Role. The type of property 'ApplicantId' on entity 'Absences' does not match the type of property 'UserId' on entity 'User' in the referential constraint 'Absences_Applicant'.
I think this is because EF try to join the two tables with the UserId of the User entity and not with UserGuid column. I thought I would make these two columns of Absence entity unique, but how I can map them together?
Thanks in advance.
The problem is your User primary key is an int, but your foreign key is a Guid.
You need to alter either your User class to have a guid for userId:
public Guid userId { get; set; }
or, update your Absence class to use an int:
public int applicantId { get; set; }

Creating a foreign key for complex type using EF 4.1 code first fluent-api

Below are my domain entities
public class User
{
public int Id { get; set; }
public string Firstname { get; set; }
public string Lastname { get; set; }
public DateTime? DateOfBirth { get; set; }
public string Username { get; set; }
public string Password { get; set; }
public string EmailAddress { get; set; }
public RoleType RoleType { get; set; }
}
public class Role
{
public int Id { get; set; }
public string Name { get; set; }
}
I have made RoleType as a complex type (to acheive enum mapping). So I could use something like context.Users.FirstOrDefault(u => u.RoleType.Value == (long)RoleTypes.Admin)
RoleTypes.Admin is an enum mapping to the Role entity
public class RoleType
{
public int Value { get; set; }
// And all the implicit operators to map with enum
}
And then I have created a mapping using fluent api
public class RoleTypeMapping : ComplexTypeConfiguration<RoleType>
{
public RoleTypeMapping()
{
Property(r => r.Value)
.HasColumnName("RoleId"); // To make sure that in RoleType property of User EF entity maps to an int column [RoleId] in database (table [Users])
}
}
Using fluent-api, I want to create a foreign key association in [Users] table for [Users].[RoleId] referencing [Role].[Id]. Please can anyone provide me guidance to acheive this
I tired adding a property of type Role and creating a mapping through fluent-api, but EF creates another column Role_Id and makes it the foreign key. I want the existing [RoleId] column (complex type) to be the foreign key
It is not possible. If you want to have association with Role table you must abandon your enum-like approach and define Users entity like:
public class User
{
public int Id { get; set; }
public string Firstname { get; set; }
public string Lastname { get; set; }
public DateTime? DateOfBirth { get; set; }
public string Username { get; set; }
public string Password { get; set; }
public string EmailAddress { get; set; }
public Role Role { get; set; }
}
First of all relations are not enums and complex types cannot contain navigation properties (as well as foreign keys).