Entity Framework 6, Model First, Primary key inheritence - entity-framework-6

With Code first i've the following :
public class Key
{
[Key, Column(Order=0), DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[Key, Column(Order = 1)]
public int CompanyId { get; set; }
}
public class Employee : Key
{
public string Name { get; set; }
public string Job { get; set; }
}
public class Department : Key
{
public string DepName { get; set; }
}
Public class Context : DbContext
{
Public Context() : base("name:DefaultConnection")
{
}
Public DbSet<Employee> Employees {get; set;}
Public DbSet<Department> Departments{get; set;}
}
This code first generates for me two tables only in the database, Employee table with two primary keys (Id, CompanyId) inherited from class Key, and Department table with two primary keys (Id, CompanyId) inherited from class Key.
I lost hours trying to do the same behavior using model first approach but i couldn't.
I'll appreciate if any Entity framwork professional can help with that :)

Related

Error while generating Model in MVC

I got the following error while generating a Model in ASP.Net:
MvcApplication1.Models.Department: : EntityType 'Department' has no key defined. Define the key for the EntityType.
department: EntityType: EntitySet 'department' is based on type 'Department' that has no keys define.
Here's a screenshot with more details:
I added the primary key to the Department table:
{
[Table("department")]
public class Department
{
public int dept id { get; set; }
public string department { get; set; }
public List<Employee> Employees { get; set; }
}
}
You need to add a [key] annotation to your deptid field:
{
[Table("department")]
public class Department
{
[Key]
public int deptid { get; set; }
public string department { get; set; }
public List<Employee> Employees { get; set; }
}
}
department table. ' {
[Table("department")]
public class Department
{
[Key]
public int dept id { get; set; }
public string department { get; set; }
public List<Employee> Employees { get; set; }
}
}`
Add key attribute, refer msdn
Another option is to change public int deptid to either public int Id or public int DepartmentId. This is a built-in EF convention, and if you use this syntax, you don't need the [Key] attribute.
https://msdn.microsoft.com/en-us/library/jj679962(v=vs.113).aspx#Anchor_1

ASP.NET Identity Foreign Key as Primary key?

In my ASP.NET MVC Application, I customized the Identity to use another table for storing the users' infos such as first name, last name and birthdate. Here's the association code:
public class ApplicationUser : IdentityUser
{
public virtual UserInfo Info { get; set; }
}
public class UserInfo
{
public int Id { get; set; }
public string FirstName { get; set;
public string LastName { get; set; }
public DateTime BirthDate { get; set; }
}
But how do you use the primary key of the ApplicationUser class as the primary key of UserInfo so that you know which user accounts the infos belong to?
The primary Key of ApplicationUser will be of a default type String, so first you will need to change your dependent class to also have a key of type string.
public class UserInfo
{
public string Id { get; set; }
public string FirstName { get; set;
public string LastName { get; set; }
public DateTime BirthDate { get; set; }
}
Then in your IdentityDbContext implementation you will need to create a mapping to create the 1:1 relationship you are after like so.
public class MyIdentityDbContext : IdentityDbContext
{
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<ApplicationUser>().HasRequired(x => x.Info).WithRequiredDependent();
base.OnModelCreating(modelBuilder);
}
}
and that should work

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

i Have a Model Class
public class Student
{
public int StudentId { get; set; }
public string StudentName { get; set; }
public ICollection<SelectListItem> CourseList { get; set; }
}
and the
public class StudentContext : DbContext
{
public DbSet<Student> Students { get; set; }
}
and i try ti use it as
List<Student> sList = db.Students.ToList();
and i am getting following error
\tSystem.Data.Entity.Edm.EdmEntityType: : EntityType 'SelectListItem' has no key defined. Define the key for this EntityType.
\tSystem.Data.Entity.Edm.EdmEntitySet: EntityType: EntitySet 'SelectListItems' is based on type 'SelectListItem' that has no keys defined.
Please suggest where i am doing wrong.
Add [NotMapped] annotation to the LIST class
[NotMapped]
public List<SelectListItem> ListItems { get; set; }
NotMapped Code first convention dictates that every property that is of a supported data type is represented in the database. But this isn’t always the case in your applications. For example you might have a property in the Blog class that creates a code based on the Title and BloggerName fields. That property can be created dynamically and does not need to be stored. You can mark any properties that do not map to the database with the NotMapped annotation such as this BlogCode property.
[NotMapped]
public string BlogCode
{
get
{
return Title.Substring(0, 1) + ":" + BloggerName.Substring(0, 1);
}
}
You can refer to the link here on EF code first Data Annotations
You should not be attempting to store SelectListItem in the database, as this is MVC specific concept. Instead create a custom entity class and use it instead;
public class Course
{
public int CourseId { get; set; }
public string CourseTitle { get; set; }
}
public class Student
{
public int StudentId { get; set; }
public string StudentName { get; set; }
public ICollection<Course> CourseList { get; set; }
}
public class StudentContext : DbContext
{
public DbSet<Student> Students { get; set; }
public DbSet<Course> Courses { get; set; }
}

EF 6 - TPC - Many-To-Many Relationship

I'm having trouble with my code-first approach to Entity Framework (6) in a project. I effectively have a database that I am attempting to write code that will cause Entity Framework to replicate. I've gotten close so far, but not 100%. The first issue is many-to-many relationship:
I have a base class called Consumer and it has just basic properties:
public abstract class Consumer
{
public Guid ID { get; set; }
[DataType(DataType.DateTime)]
public DateTime CreateDate { get; set; }
[DataType(DataType.DateTime)]
public DateTime? LastModDate { get; set; }
public int RecordStatus { get; set; }
}
I then want to use inheritance for the subsequent classes:
public class Entity : Consumer
{
[DisplayName("Entity Name")]
public string EntityName { get; set; }
[DisplayName("Phone Number"]
public string PhoneNumber { get; set; }
[DisplayName("Doing Business As"]
public string DBA { get; set; }
}
In my context class, I successfully map all of the properties to the table:
modelBuilder.Entity<Entity>().Map(m =>
{
m.MapInheritedProperties();
m.ToTable("Entity");
});
I continued this design with other classes (contacts for example):
public class Contact : Consumer
{
[DisplayName("First Name")]
public string FirstName { get; set; }
[DisplayName("Last Name"]
public string LastName { get; set; }
}
Now, obviously, a contact could be related to more than one Entity and an Entity could be related to more than one Contact. How would I code this? Only thing I could think of was to create a related class like so:
public class RelatedContact
{
public Guid ID { get; set;}
public Guid ContactID { get; set; }
public virtual Contact Contact { get; set; }
public Consumer Parent { get; set; }
public virtual Consumer Parent { get; set; }
public Guid RelationshipTypeID { get; set; }
public virtual RelationshipType RelationshipType { get; set; }
}
Then after creating the related class, I was assuming I needed to go update my Entity class like so:
public class Entity : Consumer
{
[DisplayName("Entity Name")]
public string EntityName { get; set; }
[DisplayName("Phone Number"]
public string PhoneNumber { get; set; }
[DisplayName("Doing Business As"]
public string DBA { get; set; }
public virtual ICollection<Contact> Contacts { get; set; }
}
Then, I would update my DbContext to map the many relationship, but I don't know the correct syntax or if this is even the correct way to approach this. I am trying to get the following tables to output:
<<Entity>>
ID uniqueidentifier,
CreateDate datetime,
LastModDate datetime,
RecordStatus int,
EntityName varchar(250),
PhoneNumber varchar(100),
DBA varchar(250)
<<Contact>>
ID uniqueidentifier,
CreateDate datetime,
LastModDate datetime,
RecordStatus int,
FirstName varchar(100),
LastName varchar(100)
<<RelatedContact>>
ID uniqueidentifier,
ContactID uniqueidentifier,
ParentID uniqueidentifier,
RelationshipTypeID uniqueidentifier
So, any suggestions? Am I at least headed in the right direction?
To create a many-to-many relationship, you need to use second approach. Just add navigation collection to your Entity and Contact classes. And EF will create linking table for you and track links.
public class Entity : Consumer
{
... your props
public virtual ICollection<Contact> Contacts { get; set; }
}
public class Contact : Consumer
{
... your props
public virtual ICollection<Entity> Entities { get; set; }
}

MVC No Key Defined

I am getting this error in my MVC Application:
One or more validation errors were detected during model generation:
System.Data.Edm.EdmEntityType: : EntityType 'CustomerModel' has no key defined. Define the key for this EntityType.
System.Data.Edm.EdmEntitySet: EntityType: EntitySet �Customer� is based on type �CustomerModel� that has no keys defined.
My Customer Model looks like this:
public class CustomerModel
{
public string Name { get; set; }
public int CustomerID { get; set; }
public string Address { get; set; }
}
public class CustomerContext : DbContext
{
public DbSet<CustomerModel> Customer { get; set; }
}
By default, Entity Framework assumes a key property called Id exists in your model class. Your key property is called CustomerID, so Entity Framework can't find it.
Either change the name of your key property from CustomerID to Id, or decorate the CustomerID property with the Key attribute:
public class CustomerModel
{
public string Name { get; set; }
[Key]
public int CustomerID { get; set; }
public string Address { get; set; }
}
public class CustomerContext : DbContext
{
public DbSet<CustomerModel> Customer { get; set; }
}

Resources