Using entity framework to get info from three connected tables - entity-framework

I got products table
->productID - primary
->price
->Quantity
productCategory -table
->prodcatID- primary
->prodId - foreign key
->catID - foreign key
productlanguages - table
->prodID - foreign key
->langID - forein key
->Title
So I use Entity framework and I shoud somehow get all products WITH THEIR TITLE,QUANTITYI PRICE From GIVEN CATEGORY AND FROM GIVEN LANGUAGE.
SO i should somehow combine info from all these three table
so i made my first function to get all products from given category
public List<ProductCategories> GetAllProductsForCategory(int catID)
{
using (OnlineStoreDBContext db = new OnlineStoreDBContext())
{
List<ProductCategories> lst = db.ProuctCategories.Where(x => (x.CategoryID == catID)).ToList();
}
}
So now I have a list with all productID that match this category. But now how to get the data from the other two.

See Loading Related Entities: http://msdn.microsoft.com/en-au/data/jj574232.aspx

Related

I can't manually add foreign keys in golang gorm

I am trying to add a foreign key manually in gorm but i get this error
db.Model(&models.Business{}).AddForeignKey undefined (type *gorm.DB has no field or method AddForeignKey)
am using postgres
i have tried
db.Model(&Business{}).AddForeignKey("cust_id", "customers(cust_id)", "CASCADE", "CASCADE")
you can do it with two solution that i know in GORM
#1
when you create model you do it like below:
type Business struct {
Name string
CustomersID int
Customers Customers `gorm:"foreignKey:CustomersID"` // use CustomersID as foreign key
}
type Customers struct {
ID int
Name string
}
#2
every time you want you can add foreign key like below
Client.Exec("ALTER TABLE business ADD FOREIGN KEY (cust_id)" +
"REFERENCES customers (id) ON DELETE CASCADE ON UPDATE CASCADE;")

Using IN subquery in Entity Framework using Linq

I have the following tables in my database:
- Reservation
- TrainStation
- Train
- Traveller
- Reservation_Traveller
- TrainSeats: Attributes are: Train_Id, Seat, Traveller_Id
I want to find the TrainSeats rows of a particular Reservation
I have a Reservation object that contains an ICollection<Traveller> property containing the travellers of which I want to remove their seats from the TrainSeats table. I fetched the reservation object from the database like this:
var reservation = db.Reservation.Where(r => r.Id == id).FirstOrDefault();
So I want to do something like this:
db.TrainSeats.Where(ts => ts.Traveller_Id IN reservation.Travellers)
First select the travelers id:
var ids=reservation.Travellers.Select(e=>e.Id);
Then use Contains extension method which is translated into IN in sql:
var query=db.TrainSeats.Where(ts => ids.Contains(ts.Traveller_Id));
I guess if you use the FK property and navigation properties you can do it in one query:
var query= db.Travellers.Where(e=>e.ReservationId==id).SelectMany(t=>t.TrainSeats);

Entity Framework Many TO Many Relationship with Primary Key

I have the following Schema:
User Table: (Primary Key)
UserId
CustomerId
Role Table: (Primary Key)
UserId
CustomerId
UserRole Table:
UserRoleId (UNIQUEIDENTIFIER (newsequentialid)) Primary Key
UserId
Customerid
RoleId
Those tables participate in many to many relationship (UserRole). I am using Entity Framework code first with mapping classes to define the database tables. So, In my mapping class for User Table, I have the following:
this.HasMany(u => u.Roles)
.WithMany()
.Map(m =>
{
m.MapLeftKey(new string[] { "CustomerID", "UserID" });
m.MapRightKey(new string[] {"CustomerID", "RoleID"});
m.ToTable("UserRoles");
}
);
Entity framework is failing with this message:
"One or more validation errors were detected during model generation:
CustomerID: Name: Each property name in a type must be unique. Property name 'CustomerID' is already defined.
UserRole: EntityType: EntitySet 'UserRole' is based on type 'UserRole' that has no keys defined.
is it possible to tell Code First that the Primary Key for my "UserRole" is UserRoleId?
The issue is when Entity Framework tries to create the UserRole Table, it would use all columns of MapLeftKey and MapRightKey to Create UserRole with PrimaryKey that has all those columns.
Any suggestions?
You need to model your classes similar to your DB, why don't you simply add the association tables? I mocked up your DB and there is no problem as long as you model all the tables.
Test it for yourself, create an EF project .edmx using code first from existing DB, I think the answer will be obvious.

Accessing table with only foreign Keys in Entity Data Framework

i am new to Entity Data framework
i have tables
Actions ( Actionid (pk) ,Actionname , ... )
Roles ( Roleid(pk) , Rolename , .... )
ActionRoles( Actionid(pk,fk) , Roleid(fk) ) [Mapping Table]
Please Suggest me the LINQ to get the RoleNames for Perticular ActionID
(Note : there is No class created with Name ActionRoles in entitydesigner.cs as because it doesn't have any other column name then ActionId and RoleID )
Thank you in Advance
When you have a link table like this, adding all tables to the Entity Model should create 2 way relationship Properties between the 2 end tables, hiding the link table completely allowing you to access via something like:
IEnumerable<string> roleNames = Entities.Actions
.First(a => a.Actionid == actionid)
.Roles
.Select(r => r.Rolename);
where actionid is an int variable containing the actionid you're interested in.
For a discussion of how to handle many-to-many relationships such as this (both foreign keys must be in the ActionRoles primary key as indicated in the comment to your question), see these tutorials:
For EF 4.0: http://www.asp.net/entity-framework/tutorials/the-entity-framework-and-aspnet-–-getting-started-part-5
For Ef 4.1: http://www.asp.net/entity-framework/tutorials/updating-related-data-with-the-entity-framework-in-an-asp-net-mvc-application

ADO.NET Entity : getting data from 3 tables

I have following table structure:
Table: Plant
PlantID: Primary Key
PlantName: String
Table: Party
PartyID: Primary Key
PartyName: String
PlantID: link to Plant table
Table: Customer
PartyID: Primary Key, link to Party
CustomerCode: String
I'd like to have Customer entity object with following fields:
PartyID: Primary Key
CustomerCode: String
PartyName: String
PlantName: String
I am having trouble with PlantName field (which is brought from Plant table
I connected Customer to Party and Party to Plant with associations
However I can not connect Customer to Plant with association ( because it does not have one)
I can not add Plant table to mapping, when I do that - I am getting following error:
Error 3024: Problem in Mapping Fragment starting at line 352: Must specify mapping for all key properties (CustomerSet.PartyID) of the EntitySet CustomerSet
Removing Plant association works.
Any hints or directions very appreciated.
You can get these fields by using the reference path on the Entity Object.
To get the PartyName, use this syntax: Customer.Party.PartyName
To get the PlantName, use this syntax: Customer.Party.Plant.PlantName
You can extend the Customer entity by using the public partial class:
public partial class Customer
{
public string PartyName
{
get { return Party.PartyName; }
set { Party.PartyName = value; }
}
public string PlantName
{
get { return Party.Plant.PlantName; }
set { Party.Plant.PlantName = value; }
}
}
After some research, I came across this thread on MSDN that says you can create a read-only entity, which is enough of a downside to not use it alone, but it gets worse. You will also lose the ability to update all of the models dynamically based on the schema of the database.