Entity Framework Code First create db from models - ef-code-first

I am trying to use entity framework to build the database and I need some help with the models:
The models are: Company, Departments, Users, TaskType1, TaskType2, TaskType3
public class Company
{
public Company()
{
this.Departments = new HashSet<Department>();
}
public int Id { get; set;}
public string CompanyName { get; set;}
public string Address { get; set;}
public string Phone { get; set;}
public virtual ICollection<Department> Departments { get; set;}
}
public class Department
{
public Department()
{
this.Users = new HashSet<User>();
}
public int Id { get; set;}
public string Name { get; set;}
public virtual Company Company { get; set;}
public virtual ICollection<User> Users { get; set;}
}
public class User
{
public Company()
{
}
public int Id { get; set;}
public string UserName { get; set;}
public string FullName { get; set;}
public virtual Department Department { get; set;}
}
public class TaskType1
{
public TaskType1()
{
}
public int Id { get; set;}
public string Name { get; set;}
public string Description { get; set;}
public int Priority { get; set;}
}
public class TaskType2
{
public TaskType2()
{
}
public int Id { get; set;}
public string Name { get; set;}
public string Description { get; set;}
public int Priority { get; set;}
public double EstimatedCosts { get; set;}
}
public class TaskType3
{
public TaskType3()
{
}
public int Id { get; set;}
public string Name { get; set;}
public string Description { get; set;}
public int Priority { get; set;}
public bool IsDone { get; set;}
}
the reason I need to have TaskType1, TaskType2, TaskType3 as tables is because there are different types of tasks (different data/fields is needed).
How can I connect my task types to the Company and to the Department and Users so I can get results like:
all tasks per company X
all tasks assigned to department z from company x
all tasks assigned to user w from department z from company x
P.S. The task types have common and different columns

You need to establish relationships between your models. For example, to get all tasks per company X, you would need a companyID column in each of your Tasks tables and have that be a foreign key to the Company table. Then you can set up a navigation property in the Company model:
public virtual ICollection<TaskType1> TasksType1 { get; set; }
You use an ICollection here because a company can have multiple tasks...if each company could only have one task, you could do something like:
public virtual TaskType1 TaskType1 { get; set; }
This lets you access the tasks like so:
companies = db.Companies.Include(i => i.TasksType1);
Have you checked out the Contoso University tutorial? It has a good introduction to establishing hierchical models and the associated relationships.
http://www.asp.net/mvc/tutorials/getting-started-with-ef-using-mvc/creating-an-entity-framework-data-model-for-an-asp-net-mvc-application
(This is the MVC version, there is also a WebForms version of the tutorial if you are so inclined)

Related

Enity Framework Foreign Key

I have three enities
public class Customer
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Key]
public int Customerid { get; set; }
public string Name { get; set; }
public string email { get; set; }
public string Phoneno { get; set; }
}
and second Enitity
public class Merchant
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Merchantid { get; set; }
[Required]
[RegularExpression("^[\\p{L} .-]+$", ErrorMessage = "Use letters only please")]
public string MerchantName { get; set; }
[Required]
[RegularExpression("^[\\p{L} .-]+$", ErrorMessage = "Use letters only please")]
public string BusinessName { get; set; }
[Required]
public string OfficePhno { get; set; }
}
public class Transaction
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int TransactionId { get; set; }
public int Merchantid {get; set;}
public int Customerid {get; set;}
public int Amount { get; set; }
public Customer customer {get; set;}
public Merchant merchant {get; set;}
}
in above Transaction table has two IDs Merchant ID and Customer ID i want this to foreign keys of customer and merchant table,
please explain me how to add the foreign key Constraints I went through many examples but was not able to get the answer for this
and another doubt is if i add Customer type inside Transaction table will I able to fetch details of customer in transaction table in Entity
Framework
I am trying to add Constraint by follwing code
[ForeignKey("Customerid")]
pubic virtual Customer customer {get; set;}
I am getting an exception as below
Additional information: The ForeignKeyAttribute on property 'Customer'
on type 'Dutch.Models.Transaction' is not valid. The foreign key name
'Customerid' was not found on the dependent type
'Dutch.Models.Transaction'. The Name value should be a comma separated
list of foreign key property names.
I finally did by Foreignkey constraint
My Model looks like this now
public class Customer
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Key]
public int Customerid { get; set; }
public string Name { get; set; }
public string email { get; set; }
public string Phoneno { get; set; }
public ICollection<Transaction> Transactions { get; set; }
}
public class Merchant
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Merchantid { get; set; }
[Required]
[RegularExpression("^[\\p{L} .-]+$", ErrorMessage = "Use letters only please")]
public string MerchantName { get; set; }
[Required]
[RegularExpression("^[\\p{L} .-]+$", ErrorMessage = "Use letters only please")]
public string BusinessName { get; set; }
[Required]
public string OfficePhno { get; set; }
public ICollection<Transaction> Transactions { get; set; }
}
So Customer and Merchants will have a collection of transactions
and in transaction table
public class Transaction
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int TransactionId { get; set; }
public int Merchantid {get; set;}
public int Customerid {get; set;}
public int Amount { get; set; }
[ForeignKey("Customerid")]
public Customer customer {get; set;}
[ForeignKey("Merchantid")]
public Merchant merchant {get; set;}
}

Navigation property from dependent to principal

I have two Entities
public class Person
{
public virtual int ID { get; set; }
public virtual string Name { get; set; }
public virtual Employee Employee { get; set; }
}
public class Employee
{
public virtual int ID { get; set; }
public virtual string Code { get; set; }
public virtual int PersonId { get; set; }
[ForeignKey("PersonId")]
public virtual Person Person { get; set; }
}
in my business first we create person then we create an employee by selecting a person, while selecting person for the employee i want to select only the persons who are not associated to employee, i couldn't figure how to configure the Employee property in Person Entity
If you are selecting people that aren't related to a specific employee then you shouldn't have a property for that. You should only have link to related entities. Try doing this in LINQ it should get you all people that don't have a relation to an employee.
var people = context.People.Where(x => x.Employee == null);
public class Person
{
public virtual int ID { get; set; }
public virtual string Name { get; set; }
public virtual Employee Employee { get; set; }
}
public class Employee
{
public virtual int ID { get; set; }
public virtual string Code { get; set; }
public virtual int PersonId { get; set; }
[ForeignKey("PersonId")]
[InverseProperty("Employee")]
public virtual Person Person { get; set; }
}
Think that should do it, inverse property creates the mapping so only needs to be done from one side.
Hope this is what you were looking for.
I figured out an answer, don't know if it's the best!
jobQuery = jobQuery.Where(jb => !Context.Employees.Any(emp => emp.JobId == jb.Id));

Parent and child record added on single MVC View

In ASP.NET MVC 5 and EF6 Code First, i have a case in which a student can have one to many addresses. Now i want to use Student model in View to add both the record Student and Addresses of student. But the problem is i cant add addresses of student, is there any appropriate solution for this solution
Here is the example code
public class Student
{
public Student()
{ }
[Key]
public int StudentID { get; set; }
[Required]
public string Name { get; set; }
public virtual List<Address> Address { get; set; }
}
public class Address
{
public Address()
{
}
[Key]
public int AddressID { get; set; }
[ForeignKey("Student")]
public int StudentID { get; set; }
public string Address1 { get; set; }
public string Address2 { get; set; }
public string PostalCode { get; set; }
public string State { get; set; }
public string City { get; set; }
public string Country { get; set; }
public virtual Student Student { get; set; }
}
Make Listbox for address's and Pass with List that will be really help you and can you paste controller code here?

EF Code First with One-to-Many and Many-to-Many relationships? cause cycles or multiple cascade paths

I have four models that are Family, Mother, Father, Student, I am trying to associate Father& Mother& Student with Family table and Student table associated with Mother and Father tables. Here Family table contains information about the family. Mother and Father Tables contain their personal information, and Student table contains student information + MotherID and FatherID. Which means Family table was the Primary table to Mother and Father, Student table. MotherID of Mother table and FatherID of father table were referenced to Student table.
I am using MVC 4 Entity Framework Code First,
These are my model classes.
public class Family
{
public int FamilyID { get; set; }
public string FamilyName { get; set; }
public virtual ICollection<Mother> Mothers { get; set; }
public virtual ICollection<Father> Fathers { get; set; }
public virtual ICollection<Student> Students { get; set; }
}
public class Mother
{
public int MotherID { get; set; }
public int FamilyID { get; set; }
public string FirstName { get; set; }
public string SSN { get; set; }
public virtual Family Families { get; set; }
public virtual ICollection<Student> Students{ get; set; }
}
public class Father
{
public int FatherID { get; set; }
public int FamilyID { get; set; }
public string FirstName { get; set; }
public string SSN { get; set; }
public virtual Family Families { get; set; }
public virtual ICollection<Student> Students { get; set; }
}
public class Student
{
public int StudentID { get; set; }
public int FamilyID { get; set; }
public int MotherID { get; set; }
public int FatherID { get; set; }
public string FirstName { get; set; }
public string SSN { get; set; }
public virtual Family Families { get; set; }
public virtual Mother Mothers { get; set; }
public virtual Father Fathers { get; set; }
}
Database Context Class:
public class MYContext:DbContext
{
public DbSet<Family> Families { get; set; }
public DbSet<Mother> Mothers { get; set; }
public DbSet<Father> Fathers { get; set; }
public DbSet<Student> Students { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
//modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
//base.OnModelCreating(modelBuilder);
}
}
After writing the above code I just ran the below commands on package manager console.
PM> Add-Migration InitialContext It created an InitialContext.cs class for me.
PM> Update-Database -Verbose It give me an error below
Introducing FOREIGN KEY constraint 'FK_dbo.Student_dbo.Mother_MotherID' on table
'Student' 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. See previous errors.
What am I doing wrong??
Why I am getting this error??? Please help me some one!
What is the correct way to implement one-to-many and many-to-many relationships using EF code first? Please guide me with this example.
Try adding the [key] annotation immediately above your keys. For instance, for the student, it would look like this...
public class Student
{
[key]
public int StudentID { get; set; }
public int FamilyID { get; set; }
public int MotherID { get; set; }
public int FatherID { get; set; }
public string FirstName { get; set; }
public string SSN { get; set; }
public virtual Family Families { get; set; }
public virtual Mother Mothers { get; set; }
public virtual Father Fathers { get; set; }
}
This will tell you, in detail, how to manage your model from a codefirst perspective.
http://thedatafarm.com/blog/data-access/code-first-entity-framework-4-1-videos-and-articles-on-msdn/
I have found same problem and solution at Entity Framework, Code First modeling and a cyclical reference
The exception was coming from SQL Server DB not from entity framework, that table structure with the same constraints created by hand will be invalid. Foreign key properties of Mother table (Mother.FamilyID) and Father Table (Father.FamilyID), Student table (Student.MotherID) & (Student.FatherID) are not nullable, those representing required relationships and the corresponding columns in the database are also not nullable. So DB is not allowing this model.
If I remove all these properties from model classes then automatically relationship become optional because the navigation properties can be null, So DB treated as this is another model now since the FK columns in the DB can be nullable. Seemingly this is an allowed model.
It worked for me! Use nullable types as follows
Here is the solution for cause cycles or multiple cascade paths issues:
public class Student
{
public int StudentID { get; set; }
public int FamilyID { get; set; }
public int? MotherID { get; set; } //nullable types
public int? FatherID { get; set; } //nullable types
public string FirstName { get; set; }
public string SSN { get; set; }
public virtual Family Families { get; set; }
public virtual Mother Mothers { get; set; }
public virtual Father Fathers { get; set; }
}
Finally my model becomes with foreign key properties which represent optional instead of required relationship.
really very very thanks to # https://stackoverflow.com/users/270591/slauma and
https://stackoverflow.com/users/173937/decibyte for helping me in this type issue.

How do I build a class that shares a table with multiple columns in MVC3?

I have a Job table
public class Job
{
public int JobId { get; set; }
public int SalesManagerId { get; set; }
public int SalesRepId { get; set; }
}
and a Person table
public class Person
{
public int PersonId { get; set; }
public int FirstName { get; set; }
public int LastName { get; set; }
}
My question is, how do I link the SalesManagerId to the Person (or PersonId) as well as the SalesRepId to the Person (PersonId)? The Sales Manager and Sales Rep are independent of each other. I just don't want to make 2 different lists to support the Sales Manager and Sales Rep roles.
I'm new to MVC3, but it seems public virtual Person Person {get; set; } would be the way to go, but that doesn't work.
Any help would be appreciated!
Thanks!
Change your Job class like this
public class Job
{
public int JobId { get; set; }
public virtual Person SalesManager { set; get; }
public virtual Person SalesRep { set; get; }
}
This will create the Job table with 3 columns. JobId, SalesManager_PersonID (ForiegnKey) ,SalesRep_PersonID (Foriegn key)

Resources