Comparing SQL tables and getting Values using Entity Framework - c#

I have three tables viz: Person(PersonID(INT), Personname(varchar)) , Items(ItemID(INT), Itemname(varchar)) and PersonItemAssoc(PersonItemAssoc(Int), PersonID(INT), ItemID(INT)).
PersonItemAssoc is having many to many association for personid and Itemid.
I want to get way in which if I pass the itemId, I should get all the PersonIds which dont have an association witn this ItemId in the PersonItemAssoc table.
I am using Entity Framework 4.0.
Please suggest a way for implementing this.

var peopleWithoutItem = from p in Context.Person
where !p.PersonItems.Any(pi => pi.Item.ItemId == someItemId);
select p;
Note that if you get rid of PersonItemAssoc(int) and make the PersonItemAssoc PK the compound of PersonID and ItemID then the EF can do People to Items as a many to many, instead of two 1 to many relationships.

Related

Entity Framework with table join to another database with Code First

I have an EF code first application. I have a column PersonId that I need to join with another database (warehouse) table Persons which contains all the people in our organization.
I have read that one solution is to use a view then make my entity model from the view but this seems quite painful if we have a PersonId column in many tables.
How best to return back all rows from table A joined with a table B from another database on key column PersonId, really to return PersonDisplayName from table B?
There has got to be a best practice for this situation?

Entity framework get the foreign key

I have 1:n relationship between to tables in a database: Employee (1) : Role (n)
Role has foreignKey named idEmployee
I want to create a linq statement which will get every role for a given customer. I want to make something like this:
var myQuery = from r in Role
where r.idEmployee == someId
select r;
But, r doesn't have an idEmployee property! How can I get the value of the foreign key?
If you're using EF 4.0 (.NET 4.0), and a database-first programming model with an EDMX model (visual designer), then you need to make sure to have the option Include foreign key columns in the model checked when you add tables to your EDMX model:
If you don't have this option checked, then EF 4.0 will behave the same as EF 1.0/3.5 (in .NET 3.5) which is to include a navigation property - but not the foreign key column as a separate column.
If you are using EF4.0 at least, this will give you what you need: Foreign keys in Entity Framework
If you're using EF1.0, your problem is more serious since it does not show foreign keys in model. You need to iterate through EntityKey.EntityKeyValues collection in search of valid value. But I think this would only get you value of foreign key and would not work in query (since EF would not know how to translate it to SQL query).
But since you have foreign keys, why don't you simply use NavigationProperty to navigate to Employee entity and check value there?
var myQuery = from r in Role
where r.Employee.idEmployee == someId
select r;
Use the include method on Employee class to bring back all the related roles:
var myQuery = from e in Employees.Include(emp => emp.Roles)
where e.EmployeeId == someId
select e

Perform a Linq Many to Many Query

In SQL I have 2 tables.
Sport Athlete
SportId AthleteId
SportName AthleteName
Their relation is many to many. So there is a third table that join them.
AthleteSport
AthleteId
SprortId
If i create an entity data model using the wizard the third table is disapeared and only creates the 2 main tables with the many to many relation.
how can I perform a query to find out what kind of sports athlete 'A' does? How to change them or add a new sport?
I want to use linq and c#.
Thank you.
In your Sport entity, there will be a so called "navigation property" Athletes that contains all Athletes that belong to that Sport instance.
The same is true the other way around.
Can't you do A.Sports and get that list?

Fluent NHibernate and friend relationship

I need to model a friend relationship with Fluent NHibernate. My company model has a List<Company> Related with related companies. Relations between companies are modeled in my database in a table, related which looks like this:
customer_id | related_id
Both columns is a foreign key to the PK in my customers table.
The problem is that relations are only saved once for each pair (do you call it bi-directional?).
I'm able to change the table structure if it's easier to solve in another way.
I need to map Fluent NHibernate so that when i do customer.Related(), it generates a query like:
SELECT * FROM companies LEFT JOIN related ON customer_id = id OR related_id = id
I've tried to map this in a number of different ways, the closest i've tried is:
HasManyToMany(x => x.Related)
.Inverse()
.ParentKeyColumn("customer_id")
.ChildKeyColumn("related_id")
.Table("relations")
.Cascade.All();
However, this (of course) only maps when customer_id matches.
How do I solve this?
Edit:
I think it's similar to Fluent NHibernate: How to create one-to-many bidirectional mapping?, but it does not help me much.
I think what you want to achieve is already half way done. You've mapped 2 entities with a Many2Many relation already. I wouldn't touch mapping any further.
Instead I would query what I want thru that mapping. Something like this.
function GetRelated(long id){
return Session.Query<Related>()
.Where(r=>r.Customer.Id == id || r.Related.Id == id)
.ToList();
}
A reccomendation tho, the mapped entity's name is Related and you have a related field that might sound confusing, so I'd suggest you to rename it into something else (if possible).
Hope it helps.

Defining a 1 to many relationship in Entity Framework

I'm trying to create a 1:m relationship using Entity Framework (.net 4.0) and am getting the following error:
App_Code.Model.msl(36,6) : error 3007: Problem in mapping fragments
starting at lines 6, 36:Column(s) [ProductId] are being mapped in
both fragments to different conceptual side properties.
What i have is a Products table, and a Features table. The idea is that Products have many Features. Products each have a ProductId, and the Features have a ProductId foreign key.
Now the catch is that the foreign key doesn't exist in sql server, and i don't want it to. If it did, then it all automagically works nicely.
In the EDMX designer, i created an association from the product to the feature entity, then edited the mapping details of the ProductFeature association to be based on the Features table, which i think would make it work.
Any ideas? Thanks very much.
This is a M x N relationship. Why? Because a feature can be assigned to more than one type of product.
You should have a table ProductFeatures like so:
ProductId FeatureId
1 1
1 2
2 1
2 2
Found one solution: delete the scalar property 'ProductId' from the feature entity:
http://social.msdn.microsoft.com/Forums/en-US/adodotnetentityframework/thread/a71901fb-97ec-4072-949a-c0c66a9775b1
However, in the auto-generated relationships that EF gives you if you set up the foreign key in the database, the eg 'ParentId' fields are present in the child as a scalar field.
So i'm a little confused still.
-edit- Further help:
http://www.hanselman.com/blog/CreatingAnODataAPIForStackOverflowIncludingXMLAndJSONIn30Minutes.aspx

Categories