Entity Framework 4.0 - EntityDataSource Many-To-Many Relation Query? - entity-framework

I want to perform a selection by 2 Entity ( AppRoles and AppUsers) ,
If in SQL, i would do this, For example :
SELECT u.*, r.* FROM AppUsers u ,AppRoles r WHERE u.RoleID = r.RoleID
Also it can be done using LINQ Syntax in Code-Behind.
However, i don't know how to do in EntityDataSource
Below is my mark-up :
<asp:EntityDataSource ID="edsUsers" runat="server"
ConnectionString="name=ReferralDBEntities"
DefaultContainerName="ReferralDBEntities" EnableFlattening="True"
EntitySetName="AppUsers"
Include="AppRoles"
Select="it.AppUsers, it.AppRoles"
Where="it.AppUsers.RoleID = it.AppRoles.RoleID"
>
</asp:EntityDataSource>
But it show the error.

assuming you want a list of all users in each role
and assuming you have a 3 table structure i.e. users, UserInRoles, UserRole
Then
<asp:EntityDataSource ID="edsUsers" runat="server"
ConnectionString="name=ReferralDBEntities"
DefaultContainerName="ReferralDBEntities" EnableFlattening="True"
EntitySetName="UserInRoles"
Include="UserRole, User"
Select="it.User.FullName, it.UserRole.Name">
</asp:EntityDataSource>
Job done

An older post not answered.
Try removing the Select="it.AppUsers, it.AppRoles"
Otherwise I am not sure how the relationship between your two tables is setup in the EDMX. You may want to check those also.

Related

How to use Entity Framework with a database without relationships defined

I am new to EF so please bear with me. I am using Entity Framework with an existing database in which the relationships are not defined.
Using EF, I am able to produce the model, but obviously the 'navigational properties' are not working. Is there a way I can specify the mapping between the entities?
For example, in my Product entity, I have a field CategoryID_fk (maps to Category entity). But since the relationships are not defined, I cannot load a Category while loading a Product entity.
Can someone guide me in this regard?
I do understand that it would be preferable to refactor our database but I am unable to do that now. Thanks in advance.
This link is very useful.http://www.entityframeworktutorial.net/
I think field names are not suitable conventions.Try to change field name as CategoryId or Category_CategoryId .I think it will work
Yes, you can do a group join. Basically you will retrieve Products and Category in separate queries and take an approach as indicated in this answer.
Something along these lines:
var productCategoryList = products.GroupJoin
(
categories,
p=> p.productId,
c=> c.CategoryId,
(p, c) => new ProductCategory
{
//Create your Product Category model here
}
).AsEnumerable();

Entity Framework, Computed Entity Field

Is it possible to include a computed field in an EF entity? Example, lets say I have a shop selling products, and the products are grouped into categories.
When the list of categories is displayed for editing to the administrator of the shop I wish to list the number of products in each category as part of the list.
In NHibernate I would use a formula e.g.
<property name="Products" formula="dbo.Category_NumProducts(id)" />
I can't work out if something similar is possible for EF. I know I could make a category view and map this to a second entity but that seems wrong as its almost a complete duplication.
EDIT: If this isn't possible in EF, then what is the best way to accomplish this?
Unfortunately if your Category table doesn't have this as computed column you will not be able to map it without creating second entity - it leads to database view, defining query in EDMX or perhaps Query view in EDMX (but Query view may not work because you require aggregate function to be computed).
Edit:
IMHO the simplest solution (and also the best) is simply creating a ViewModel (some non mapped class) and use projection in Linq query:
var query = from c in context.Categories
where ...
select new CategoryView {
Id = c.Id,
Name = c.Name,
...
Products = c.Products.Count()
};

Entity Framework code first aspnet_Users mapping / joins

I was wondering with Entity Framework 4.1 code first how do you guys handle queries that involve an existing aspnet_Users table?
Basically I have a requirement for a query that involves the aspnet_Users so that I can return the username:
SELECT t.Prop1, u.Username
FROM Table1 t
INNER JOIN aspnet_User u ON t.UserId = u.UserId
Where t.Prop2 = true
Ideally in linq I would like:
from t in context.Table1
join u in context.aspnet_Users on t.UserId equals u.UserId
where t.Prop2 = true
But I'm not sure how to get aspnet_Users mapping to a class User? how do I make aspnet_Users part of my dbset ?
Any help would be appreciated, thanks in advance
Don't map aspnet_Users table or any other table related to aspnet. These tables have their own data access and their own logic for accessing. Mapping these tables will introduce code duplication, possible problems and breaks separation of concerns. If you need users for queries, create view with only needed information like id, user name, email and map the view. The point is that view will be read only, it will contain only allowed data and your application will not accidentally modify these data without using ASP.NET API.
First read Ladislav's answer. If you still want to go ahead : to do what you want would involve mapping the users and roles and members tables into the codefirst domain - which means writing a membership provider in code-first.
Luckily there is a project for that http://codefirstmembership.codeplex.com/ although its not a perfect implementation. The original is VB, look in the Discussion tab for my work on getting it running in c# MVC.
I'm working with the author on a better implementation that protects the membership data (password, last logged on date, all of the non-allowed data) but allow you to map and extend the user table. But its not ready yet!
You don't really need to use Entity Framework to access aspnet_membership provider accounts. You really just need to create an instance of the membership object, pass in a unique user identifier and a Boolean value indicating whether to update the LastActivityDate value for the user and the method returns a MembershipUser object populated with current values from the data source for the specified user.
You can then access the username by using the property of "Username".
Example:
private MembershipUser user =
Membership.GetUser(7578ec40-9e91-4458-b3d6-0a69dee82c6e, True);
Response.Write(user.UserName);
In case you have additional questions about MembershipProvider, you can read up on it on the MSDN website under the title of "Managing Users by Using Membership".
Hope this helps you some with your requirement.

WPF data binding using ADO.NET Entity Framework 4

Good Morning All,
I'm having a small conceptual problem with ADO.NET EF4 (and perhaps ORM in general) and I was hoping someone could help fill in the gaps in my knowledge.
In my example I have a normalised Database with two Tables: User & Company
User //
UserId(PK),
CompanyId(FK),
FirstName,
LastName
Company //
CompanyId(PK),
CompanyName
I have created an Entity Data Model to match these tables in my application.
I now need to display a list of Users along with their Company Name in a listbox control. I realise I can display a list of Users using:
DatabaseEntities db = new DatabaseEntities();
Listbox1.ItemSource = db.Users;
Obviously the problem here is that it will display the CompanyId field as oppose to the CompanyName.
My question is; What is the best approach to get at the CompanyName Field? Do I create a stored procedure to return a different record set? Create a new entity with the fields I require?
I can think of several approaches but I'm not sure which is best practice.
Any help is greatly appreciated!
Figured it out, i wasn't aware you could specify bindings like:
<TextBlock Grid.Column="3" Padding="10,20,0,0" Text="{Binding Company.CompanyName}"/>

Entity framework linq to entities

Previously when I wanted obtain related data in an sql query I would join tables, however now in linq to entities I want to get data from a table that is related to the table through another table. I don't know how to perform this sort of query in linq to entities. If someone could help that would be good.
The example is a table named person which has a relationship to table users which is related to table roles. I want to be able to obtain a person that has a particular role. Since person is only related to user and indirectly through user to role, I'm not sure of the query. Also using navigation properties doesn't get me all the way there either.
Any information would be good. Here is an example of the database structure:
db structure http://img194.imageshack.us/img194/4540/persons.jpg
If you using the generator in VS (ie, drap drop the data table and diagram and keys are all set in db), then the thing you are asking could be already there automatically.
e.g.
from Person in Context.Persons
where Person.Name == "PETER PAN"
select Person.User.Role.RoleName;
Exact name need to refer to the code generator, but this is the idea. Linq to entities will help to map foreign keys and those for you.
Edit
Actually I haven't tried using include. But according to msdn:include method, the include should show the object hierarchy to work. So, for your query to work, try:
from c in db.Persons.Include("aspnet_Users").Include("aspnet_Roles")
where c.aspnet_Users.aspnet_Roles.RoleName == "Role" select c
And moreover, will you consider start from roles?
from r in db.aspnet_Roles
where r.RoleName == "ROLE"
select r.aspnet_Users.Persons
(from u in db.aspnet_Users.Include("Person")
from c in db.aspnet_Roles
where c.RoleName == "role"
select u.Persons);
Worked it out thanks for trying though.