Entity framework get the foreign key - c#

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

Related

.net Entity framework eager loading with custom Id association

New to C#.ne. How to do eager loading if the Foreign Id doesn't match the class name?
I saw this example in the official doc.
var blogs1 = context.Blogs
.Include(b => b.Posts)
.ToList();
I believe under the hood, this one does something like
LEFT OUTER JOIN Post ON Blog.Id = Post.BlogId
In my case, my blog in DB doesn't use id as the primary key, it uses blog_id and the post may use p_id as the primary key and b_id as the foreign key.
How to customize the include with the unconventional key?
You don't need to customize this Entity framework will handle this by Navigation properties (provide a way to navigate an association between two entity type) you have in your model (recommended as they map to foreign keys in the database).
The SQL statement generated from the above LINQ statement may look like this as per your schema:
SELECT * FROM Blog JOIN Post ON Blog.Blog_Id = Post.B_Id

Delete selected entity object from gridview,where foreign key table block it

These are the tables Employee, EmployeeTicket, Ticket in my SQL Server database:
http://i62.tinypic.com/709q50.png
And this is how its seen in my Entity Framework model
http://i57.tinypic.com/30w9fup.png
As you see my foreign key table becomes a navigation property and it's OK I found a way to use it.
// Use a LINQ expression to find the selected product.
int selectedID = (int)GridViewTicketHistory.SelectedDataKey.Value;
var matches = from p in entities.Employees
where p.ID == selectedID
select p;
// Execute the query and return the entity object.
Employee emp = matches.Single();
// Delete the entity object.
entities.Employees.DeleteObject(emp);
// Commit the changes back to the database.
entities.SaveChanges();
editCustomerTicket();
The problem is I get an error:
The DELETE statement is in conflict with the constraint REFERENCE "FK_EmployeeTicket_Employee". The conflict occurred in the table "dbo.EmployeeTicket", column 'ID' database "TrackUser"
Which means I can't delete ID from Employee and I think I should first delete the ID in foreign key table. How can I achieve that? Or is there any simple change I can do to get rid of this error?
u can try to make EmployeeTicket ID as allows NULL depends on how set the colums properties
for more info take a look at here

Removing a row from table with two foreign keys entity framework

I have a table which consists of only 2 foreign keys as columns. These keys in the table represent a many to many association between 2 other tables. For example: The table is RoleGroup, and the only 2 columns are GroupId and RoleId, both foreign keys to Group and Role tables, respectively. The generated EF object from database didn't create the RoleGroup object, only navigation properties with the other tables. I can insert data in RoleGroup table in EF as follows:
Group grp = context.Groups.Where(g => g.Id == 8);
Role role = context.Roles.Where(r => r.Id == '001c');
grp.Roles.Add(role);
context.SaveChanges();
Now, how do I remove a row within the table RoleGroup in EF e.g. remove a group (with Id = 5) from a role with Id say '001b'?
Entity framework, like most ORM's abstracts away link tables. Presuming that you've got everything set up correctly you can remove the record by removing the link.
Role role = //Whatever Role;
group.Roles.Remove(role);

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

Entity Framework model and foreign key property

I have 2 tables that I import to EF model.
First table has a property [section] that acts as foreign key to the second table.
When I map this property in model to the table and try to compile I get this error:
Problem in Mapping Fragments starting
at lines 158, 174: Non-Primary-Key
column(s) [Section] are being mapped
in both fragments to different
conceptual side properties - data
inconsistency is possible because the
corresponding conceptual side
properties can be independently
modified.
If i remove this property from the model it passes, but when I query the data I don't have the section field.
I know that I can get it by using the navigation field and reading this property from the second table, but to make it work I must include the other table in my query.
var res = from name in Context.Table1.Include("Table2")...
Why do I need to include the association just for one field?
UPDATE
To make it more clear:
Table 1 has fields:
ItemId - key
section - foreign key
title
Table 2 has fields:
SectionId - key
Name
When I set the associations the section property from the first table must be removed.
What are your Primary Keys and is one Store Generated? I suspect you are missing a PK or an Identity somewhere.
Tip: One alternative when having mapping problems is to create the model you want in the EDMX designer and then ask it to create the database for you. Compare what it creates to what you have made in SQL and it's often easy to spot the mistakes.
In EF 4 you can use FK associations for this.
In EF 1 the easiest way to get one field from a related table is to project:
var q = from t1 in Context.Table1
where //...
select new
{
T1 = t1,
Section = t1.Section.SectionId
};
var section = q.First().Section;
If it's a key property, you can get the value via the EntityKey:
var t1 = GetT1();
var section = (int)t1.SectionReference.EntityKey.Values[0].Value;
Generally, I don't like this last method. It's too EF-specific, and fails if your query MergeOption is set to NoTracking.

Categories