Code First Foreign Key Configuration in Many to Many Relationships - asp.net-mvc

I have created two table.
Table 1: Parent table with ParentId and ParentName fields.In this ParentId is primary key.
Table 2: Child table with ChildId and ChildName fields.In this ChildId is primary key.
I want to get the ParentId and ChildId into another table.So icreated table in the name MappingParentChild with ParentId1,ChildId1.I want this ParentId1 and ChildId1 as foreign key.
How can i achive this.
public class Parent
{
public int ParentId { get; set; } //Primary key
public string ParentName { get; set; }
}
public class Child
{
public int ChildId { get; set; } //Primary key
public string ChildName { get; set; }
}
public class MappingParentChild
{
public int Id { get; set; }
public int ParentId1 { get; set; } // want Foreign key for Parent(ParentId)
public int ChildId1 { get; set; }// want Foreign key for Child(ChildId)
}
public class MappingParentChildConfiguration :EntityTypeConfiguration<MappingParentChild>
{
public MappingParentChildConfiguration()
{
ToTable("MappingParentChild");
Property(m => m.Id).IsRequired();
Property(m => m.ParentId1).IsRequired();
Property(m => m.ChildId1).IsRequired();
}
}
How can i do this.Please help me.

public class Parent
{
public int ParentId { get; set; }
public string ParentName { get; set; }
public virtual ICollection<MappingParentChild> parent{ get; set; }
}
public class Child
{
public int ChildId { get; set; }
public string ChildName { get; set; }
public virtual ICollection<MappingParentChild> child { get; set; }
}
public class MappingParentChild
{
public int Id { get; set; }
public int ParentId1 { get; set; }
public int ChildId1 { get; set; }
public virtual Parent pt{ get; set; }
public virtual Child Ch{ get; set; }
}
public class MappingParentChildConfiguration : EntityTypeConfiguration<MappingParentChild>
{
public MappingParentChildConfiguration()
{
ToTable("MappingParentChild");
Property(m => m.Id).IsRequired();
HasRequired(m => m.pt).WithMany(e => e.parent).HasForeignKey(m => m.ParentId );
HasRequired(m => m.ch).WithMany(e => e.child ).HasForeignKey(m => m.ChildId );
}
}

Related

Foregin key relationship error

I have following model classes
Each Item has 4 languages in perticular languages table
public class Item
{
[Key]
public int Id { get; set; }
public DateTime? ExpireDate { get; set; }
}
public class ItemLanguage
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
[ForeignKey("Language")]
public int LanguageId { get; set; }
[ForeignKey("Item")]
public int ItemId { get; set; }
public Language Language { get; set; }
public Item Item { get; set; }
}
Each item library has 4 languages in perticular language table
public class ItemLibrary
{
[Key]
public int Id { get; set; }
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd MMM yyyy}")]
public DateTime? ExpireDate { get; set; }
}
public class ItemLibraryLanguage
{
[Key]
public int Id { get; set; }
[Required]
public string Name { get; set; }
[ForeignKey("Language")]
public int LanguageId { get; set; }
[ForeignKey("ItemLibrary")]
public int ItemLibraryId { get; set; }
public ItemLibrary ItemLibrary { get; set; }
public Language Language { get; set; }
}
Now I want to add items to the ItemLibraryItems table.
It need to save the ItemId and the ItemLibraryId in this table(Not the languageId). When displaying the selected items for the library it needs to show the according to the selected language in login.
public class ItemLibraryItem
{
[Key]
public int Id { get; set; }
[ForeignKey("ItemLibrary")]
public int ItemLibraryId { get; set; }
[ForeignKey("Item")]
public int ItemId { get; set; }
public ItemLibrary ItemLibrary { get; set; }
public Item Item { get; set; }
}
But when I'm trying to create the Controller by using ItemLibraryItem as the model class it gives the error
The entity types 'ItemLibraryItem' and 'ItemLibraryLanguage' cannot share table 'ItemLibraryLanguages' because they are not in the same type hierarchy or do not have a valid one to one foreign key relationship with matching primary keys between them.

how to create foreign key use migration code first (one to many relationship)

I have 2 classes:
public class Retete
{
public Retete() { }
public int ID { get; set; }
public string Nume { get; set; }
public string Categorie { get; set; }
public string Grupa { get; set; }
public string Descriere { get; set; }
public string Ingrediente { get; set; }
public string Preparare { get; set; }
//Configure 1 to many relationship
//Foreign Key
[ForeignKey("GrupaIndivizi")]
public int GrupaID { get; set; }
[ForeignKey("GrupaID")]
public virtual GrupaIndivizi GrupaIndivizi { get; set; }
}
and
public class GrupaIndivizi
{
public GrupaIndivizi(){}
[Key]
public int GrupaID { get; set; }
public string NumeGrupa { get; set; }
public virtual ICollection<Retete> Retetes { get; set; }
}
and the table that are created
My question is how to make GrupaID from Retetes table to be a foreign Key?
One way to make a foreign key in entity framework is: beside the Id of the key you need to have an object of that type. Check if this works.
[Table("Retete")]
public class Retete
{
public Retete() { }
public int ID { get; set; }
public string Nume { get; set; }
public string Categorie { get; set; }
public string Grupa { get; set; }
public string Descriere { get; set; }
public string Ingrediente { get; set; }
public string Preparare { get; set; }
//Configure 1 to many relationship
//Foreign Key
[ForeignKey("GrupaIndivizis")]
public int GrupaIndiviziID { get; set; }
public GrupaIndivizi GrupaIndivizi { get; set; }
}
I would also recommed to get the tables some more suitable names and don't let EF generate the names. This can be done by the Table attribute.
Your FK didn't generate corectly because he was trying to bind to a GrupaIndivizi table but you have GrupaIndivizis.

Fluent API One to Many mapping table

It's really helpful if anyone could explain me how to create a mapping (associated)table for one to many relationship using Fluent API.`
public class Category
{
public int ID { get; set; }
public string Name { get; set; }
public List<Image> Images { get; set; }
}
public class Image
{
public int ID { get; set; }
public string Name { get; set; }
public List<Category> Category{ get; set; }
The mapping table should contain CategoryID and ImageID.
The solution should be something similar to this. (This is for many to many)
modelBuilder.Entity<Category>()
.HasMany(c => c.Images).WithMany(i => i.Categories)
.Map(t => t.MapLeftKey("CategoryID")
.MapRightKey("ImageID")
.ToTable("CategoryImage"));
I want Fluent API to create new mapping table for the below relationship.
public class Category
{
public List<Image> Images{get; set;}
}
public class Image
{
public Category Category{ get; set; }
}
Adding NewTable:
modelBuilder
.Entity<NewTable>()
.HasRequired(_ => _.Category)
.WithMany()
.HasForeignKey(_ => _.CategoryId);
modelBuilder
.Entity<Image>()
.HasRequired(_ => _.NewTable)
.WithMany(_ => _.Images)
.HasForeignKey(_ => _.NewTableId)
public class NewTable
{
public int ID { get; set; }
public int CategoryId { get; set; }
public List<Image> Images { get; set; }
public virtual Category Category { get; set; }
}
public class Image
{
public int ID { get; set; }
public string Name { get; set; }
public List<Category> Categories { get; set; }
public int NewTableId { get; set; }
public virtual NewTable NewTable { get; set; }
}

Passing multiple models into view MVC

Relatively new to MVC and can't figure out how to pass data from multiple models into a single view. I know I need to use a view model, but I can't figure out what to do in the controller.
Models:
public class Child
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.None)]
public int ChartNumber { get; set; }
[Display(Name = "First Name")]
public string FirstName { get; set; }
[Display(Name = "Last Name")]
public string LastName { get; set; }
public string City { get; set; }
public string State { get; set; }
[Display(Name = "Zip Code")]
public int ZipCode { get; set; }
public string Ethnicity { get; set; }
public string Referral { get; set; }
[Display(Name = "Recommended Re-evaluation")]
public bool ReEval { get; set; }
[Display(Name = "Hearing Aid Candidate")]
public bool HaCandidate { get; set; }
[Display(Name = "Fit With Hearing Aid")]
public bool FitHa { get; set; }
public virtual List<ChildEval> ChildEvals { get; set; }
}
public class ChildEval
{
[Key]
public int ChildEvalId { get; set; }
public DateTime Date { get; set; }
public int PtaRight { get; set; }
public int PtaLeft { get; set; }
public int UnaidedSiiRight { get; set; }
public int UnaidedSiiLeft { get; set; }
public int AidedSiiRight { get; set; }
public int AidedSiiLeft { get; set; }
public int ChartNumber { get; set; }
public virtual Child Child { get; set; }
}
}
DbContext
public class UnitedContext : DbContext
{
public UnitedContext() : base("name=UnitedContext")
{
}
public System.Data.Entity.DbSet<United.Models.Child> Children { get; set; }
public System.Data.Entity.DbSet<United.Models.ChildEval> ChildEvals { get; set; }
}
ViewModel:
public class ChildViewModel
{
public class Child
{
public string FirstName { get; set; }
}
public class ChildEval
{
public int PtaRight { get; set; }
}
}
ViewModelController? :
public class ViewModelController : Controller
{
//
// GET: /ViewModel/
public ActionResult Index()
{
return View();
}
}
}
I'm stuck on how to create the controller for the viewmodel and how to actually get the data into the view. Any help would be greatly appreciated!
Don't have a controller called ViewModelController. Controller is the handler between database and the view. Therefore the name of the controller should tell the programmer what kind of data the controller is controlling. By default, it also indicates the subsite you are in your web application ( ViewModelController would yield http://mysite/ViewModel/ ).
Since you are handling children, I'm calling it ChildrenController for now.
Generally a good idea is to wrap your 2 models into one viewmodel and work with that. In this case Model != ViewModel, model is the database model of the entity while ViewModel is the one that's passed to/from the view.
public class Child
{
public int ID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
public class SomeOtherModel
{
public int ID { get; set; }
public int SomeInteger { get; set; }
public int SomeOtherInteger { get; set; }
}
public class ChildViewModel
{
public Child Child { get; set; }
public SomeOtherModel SomeOtherModel { get; set; }
public ChildViewModel(Child child, SomeOtherModel s)
{
Child = child;
SomeOtherModel = s;
}
}
In your controller
public class ChildrenController : Controller
{
//
// GET: /Children/
public ActionResult Index()
{
Child child = /*Fetch the child from database*/;
SomeOtherModel someOther = = /*Fetch something else from database*/;
ChildViewModel model = new ChildViewModel(child,someOther);
return View(model);
}
}
View:
#model ChildViewModel
#Html.EditorFor(model => model.Child.FirstName)
#Html.EditorFor(model => model.Child.LastName)

Entity Framework Fluent API

My Entities are as follows...
public class Project{
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public virtual ICollection<Survey> Surveys { get; set; }
}
public class Survey{
public int Id { get; set; }
public int ProjectId { get; set; }
public string Name { get; set; }
public virtual Project Project { get; set; }
}
public class Category{
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<Survey> Surveys { get; set; }
}
public class SurveyCategory{
public int Id { get; set; }
public int SurveyId{ get; set; }
public int CategoryId { get; set; }
public string Name { get; set; }
public virtual Survey Survey { get; set; }
public virtual Category Category { get; set; }
}
A project will have list of Surveys, A Survey will have only one Category, A Category can have multiple Survey, SurveyCategory is the table where I am storing Survey + Category link.
Can anyone direct me to what would be appropriate Fluent API code will be for this to map properly.... So far I have this....
protected override void OnModelCreating(DbModelBuilder modelBuilder){
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
modelBuilder.Entity<Project>().HasMany(project => project.Surveys);}
hi I hope I understood what you are looking for.
First of al you should do a few changes to your model
public class Project
{
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public virtual ICollection<Survey> Surveys { get; set; }
}
public class Survey
{
public int Id { get; set; }
public int ProjectId { get; set; }
public int CategoryId { get; set; }
public string Name { get; set; }
public virtual Project Project { get; set; }
public virtual Category Category { get; set; }
public virtual ICollection<SurveyCategory> SurveyCategory { get; set; }
}
public class Category
{
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<Survey> Surveys { get; set; }
public virtual ICollection<SurveyCategory> SurveyCategory { get; set; }
}
public class SurveyCategory
{
public int Id { get; set; }
public string Name { get; set; }
public int SurveyId { get; set; }
public virtual Survey Survey { get; set; }
public int CategoryId { get; set; }
public virtual Category Category { get; set; }
}
And then on the model creating you should do this
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Project>()
.HasMany(p => p.Surveys)
.WithRequired(u => u.Project);
modelBuilder.Entity<Category>()
.HasMany(p => p.Surveys)
.WithRequired(u => u.Category);
modelBuilder.Entity<Category>()
.HasMany(p => p.SurveyCategory)
.WithRequired(u => u.Category)
.HasForeignKey(k => k.CategoryId)
.WillCascadeOnDelete(false);
modelBuilder.Entity<Survey>()
.HasMany(p => p.SurveyCategory)
.WithRequired(u => u.Survey)
.HasForeignKey(k => k.SurveyId)
.WillCascadeOnDelete(false);
}
I hope this helps

Resources