MVC - Linking two Models using a foreign key - asp.net-mvc

How would I add a foreign key linking my Club class and my ClubEvent class together in a one-to-many relationship where Club is the parent class and ClubEvent is the child.
These are the models I am using
public class Club
{
// Class to manage a single Club
[Key]
public int ClubID { get; set;
}//end Club
public class ClubEvent
{
[Key]
public int EventID { get; set; }
}
I want to connect these two tables so I can add events for a club so I can display only the relevant events for each club

This is pretty basic MVC, and if you need help with this stuff in the future please complete this tutorial: http://www.asp.net/mvc/overview/getting-started/getting-started-with-ef-using-mvc/creating-an-entity-framework-data-model-for-an-asp-net-mvc-application it is great!
Since ClubEvent is a 'child' of Club (meaning one club can have one or many events) you want to have the reference to the parent in the child. So, you will add a reference to clubEvent linking each instance of that object to the appropriate club. Add this to your ClubEvent Object..
public int ClubID {get; set;}
[ForeignKey("ClubID")]
public virtual Club Club {get;set;}
By adding the navigation property (virtual Club Club) you will be able to make a call to the parent object from the ClubEvent child. (club)this.ClubEvent.
displaying this is easily achieved by querying the ClubEvents table with the parent Club ID. Like:
var events = db.ClubEvents.Where(e => e.ClubID == id)
Where 'id' is the ClubID passed to the method in your controller.
Hope this helps, if you have any issues check this link out because it has great examples for every relation type in MVC.
http://www.asp.net/mvc/overview/getting-started/getting-started-with-ef-using-mvc/creating-a-more-complex-data-model-for-an-asp-net-mvc-application

Related

C# Entity Framework Table Per Type adding unwanted column in base table

In C# I'm using Entity Framework and MVC and have:
public class Part
public class FinishedGoodsPart: Part
public int? ProductLineId { get; set; }
public class CompetitorPart : Part
public int? ProductLineId { get; set; }
public class OEPart: Part
public class ProductLine
public virtual ICollection<Part> Parts { get; set; }
Observe that FinishedGoodsPart and CompetitorPart have a ProductLine, but OEPart does not.
This puts a column called ProductLine_Id in the FinishedGoodsPart and CompetitorPart tables, as I expect and want, but also puts column ProductLine_Id in table Part (which I do not want).
How do I prevent E.F. from adding column Part.ProductLine_Id? Is there a better design?
The goal is that an instance of the ProductLine model object will have a list of all parts which belong to that product line (whether they are competitor or finished goods parts). But an OEPart is not allowed to have a ProductLine set.
FinishedGoodsPart objects will have a lot of attributes, whereas CompetitorPart will have very few, therefore I don't want to store all part records in a single database table.

Entity Framework Mapping. Multiple Foreign keys

I have two tables
People Relation
------------- -----------------
Id (int) Id (int)
Name (string) ParentPeopleId (int)
ChildPeopleId (int)
I need to get all people by Relation table with union all.
The relation table has two foreign keys. And there is one problem with mapping them. The mapping is one to many. People has many Relation, Relation has one People.
I mapped them like this:
HasRequired(r=> r.People).WithMany(p=>p.Relation).HasForeignKey(r=>r.ChildPeopleId);
So, how can I map the second foreign key?
Per each FK column in your Relations table you should have a navigation property in your Relation entity (this is not mandatory, but what is mandatory is have at least one navigation property between the entities involve in the relationship). In this case you have two relationships between People and Relations, and a navigation property represents one end in an relationship. Your model could be this way:
public class Relation
{
public int Id {get;set;}
public int ParentPeopleId {get;set;}
public int ChildPeopleId {get;set;}
public virtual People ParentPeople {get;set;}
public virtual People ChildPeople {get;set;}
}
public class People
{
public int Id {get;set;}
public string Name {get;set;}
public virtual ICollection<Relation> ParentRelations {get;set;}
public virtual ICollection<Relation> ChildRelations {get;set;}
}
And the Fluent Api configurations like this:
HasRequired(r=> r.ParentPeople ).WithMany(p=>p.ParentRelations ).HasForeignKey(r=>r.ParentPeopleId);
HasRequired(r=> r.ChildPeople).WithMany(p=>p.ChildRelations ).HasForeignKey(r=>r.ChildPeopleId );
Now if you don't want to work with one of the collection navigation properties in your People entity, you can create an unidirectional relationship. For example if you don't want ParenRelations navigation property, you can configure that relationship as follow:
HasRequired(r=> r.ParentPeople).WithMany().HasForeignKey(r=>r.ParentPeopleId);
Update
Let me start first with a suggestion. I thing your table Relation is not playing any role is you have only those columns. If a person con only have a parent I would change your model to the following:
public class People
{
public int Id {get;set;}
public string Name {get;set;}
public int ParentId {get;set;}
public virtual People Parent {get;set;}
public virtual ICollection<People> Children {get;set;}
}
And you relationship configuration would be:
HasOptional(r=> r.Parent).WithMany(p=>p.Children).HasForeignKey(r=>r.ParentId);
Now going back to your current model, EF sees your ChildPeopleId property as an simple scalar column, it doesn't know it's a FK column, that's way I suggested above map two relationship instead one.
Another thing, with the below line
var Peoplelist = MyDbContext.People.Include(p=>p.Relations.Select(r=>r.People)).ToList();
You are telling to EF that you want to load the Relation entities related to a People, but also you want to load the People related with each Relation, which is at the same time the same People where the Relation came from, so, you don't need to do the last select, if your data is properly related, that People navigation property is going to be loaded when you execute your query,so, that query should be this way:
var Peoplelist = MyDbContext.People.Include(p=>p.Relations).ToList();

set relationship in models without DB Context File

I am developing an app where i am using MVC in Presentation layer so I have to define model classes in it.....and because of that I want relationship in that models.
How can we define relationship in model without Dbcontext class file.
I don't exactly understand what you are asking for, but I will take a shot.
EF creates relationships in models by having a reference to the related model(s).
Say you have models Cart and Item. A Cart can contain many Items, and any one Item can only belong to one Cart. This would be a one-to-many relationship.
public class Cart
{
public int CartId {get;set;}
//other properties
public List<Item> Items {get;set;}
}
public class Item
{
public int ItemId {get;set;}
// other properties
public Cart Cart {get;set;}
}
So from your Cart class you can fetch any Items it contains, and from any of those Items you can get the Cart that contains them.
Again, not sure if this is what you are asking for, and this is very quickly thrown together, but hopefully it helps.

mvc accessing a different model from the strongly typed provided

so I'm writing to see what the best way is to deal with this ish that I have.
I have 3 models and a view that has a strongly typed using one of the models.
Here are the models:
public class Car{
public int CarId
}
public class User{
public int UserId
}
public class UserCar{
public int UserId
public int CarId
:
:
}
View would be strongly typed with Cars model to provide all the details of the car when the view is visited. But in it I want to have an indicator (maybe a text) that says that the User already has/owns the car which will depend on the UserCar model mapping.
Any thoughts?
I think you might be able to solve this by passing a strongly typed UserCar Model instead of the cars model and updating the UserCar model to have instances of the User and Car objects for example:
public class UserCar{
public User UserId
public Car CarId
:
:
}
this way you can check if userId is null as an indicator.
Just an idea...

asp.net mvc automapper parsing

let's say we have something like this
public class Person
{
public string Name {get; set;}
public Country Country {get; set;}
}
public class PersonViewModel
{
public Person Person {get; set;}
public SelectList Countries {get; set;}
}
can automapper be used to perform to parse from Person into PersonViewModel and back ?
Don't use AutoMapper for this - it's not worth it. For example, in the cases where you have a validation failure and you show the form again - AutoMapper is not executed here (usually). We usually go two routes:
If the list is not context-specific, create an HtmlHelper that queries some ISelectListProvider for the select list items: Html.DropDownList(). You'd use your IoC container of choice to locate the personListProvider, query for the list of items, and populate the dropdown list.
If the list is context-specific, just construct the list in the controller action
It sounds like you want to send a Person to the view via the PersonViewModel which has all the bonus info you need to generate and return a new (or updated) Person object.
If this is correct, I don't think you need automapper at all. From what I understand of automapper it is for mapping collection of related objects to a more view model type of state, but in this case, you are sending a Person to the client and trying to receive a Person back. In this case, it seems easier to use your view model to populate the page, but have the page return a Person instead (or extract the updated Person from the view model to save a few keystrokes).
EDIT: That being said, yes you should be able to use automapper to move the info around. Its just a unnecessary layer for this easy scenario.
if one chose to, you could do this:
public class Person
{
public string Name {get; set;}
public Country Country {get; set;}
public Country[] GetCountries
{
... add method for countries here
}
}
Then in your ViewModel you can have your select list pull data from that collection.
public class PersonViewModel
{
public Person Person {get; set;}
public Country[] Countries {get; set;}
public SelectList Countries { get{ .. add new select list code here getting vals from Countries..}}
}
Again, this is for context sensitive lists. You are however muddling concerns a wee bit here (should a person get a list of countries?)

Resources