View with Not exists join to be used in Entity Framework - asp.net

I need to create a view in SQL Server and to use it in a GridView on my .aspx page.
The view is mapped in my application through Entity Framework.
Here's my example:
SELECT User.UserName, User.UserId
FROM User
WHERE NOT EXISTS (SELECT UsersInRoles.RoleId FROM UsersInRoles
WHERE UsersInRoles.UserId = User.UserId AND UsersInRoles.RoleId = 'AdminRole')
The relation between User and UsersInRoles table is one-to-many.
I need to be able to pass the AdminRole value in my ASP.NET application.
I cannot use parameters in a view (i.e. using #Role is not allowed).
Only views and tables can bind to a GridView so a stored procedure (where a parameter
could be an option) is not good here.
Is there a workaround to use a LEFT OUTER JOIN maybe instead of the NOT EXISTS?
This way, having a JOIN on the UsersInRoles table, I could map the fields from UsersInRoles through Entity Framework in my application and I could add conditions there (with EntityDataSource.Where clause).

For Exists, use the Any extension method in LINQ. For Not Exists, use !Any.
var query = from user in User
where !user.UsersInRoles.Any(role => role.RoleId == 'AdminRole')
select new {user.UserName, user.UserId};

I'm quite new in EF, but I know that we can use stored procedures (or functions) in it.
Try read this

Related

Use stored procedures in MVC 5 & Entity Framework 6 code-first

I am working on my first ASP.NET MVC 5 application and I'm not sure how to call my stored procedures. When I started the project, I was using ADO.NET Entity Data Model, EF Designer, when creating the model I chose the tables and the stored procedures I wanted and it worked fine. For example, if I wanted to use a stored procedure called 'usp_RhAffSelect' I would simply do:
using (EmployeModele db = new EmployeModele())
{var AffectationEmploye = db.usp_RhAffSelect(employeID, sequence).ToList();
...
and the result from the select query would be stored in 'AffectationEmploye'
But then I had to change my model to code first instead of EF Designer. I selected the tables I wanted (which are RhAff,RhEmp and RhEve). So I have my MainModel.cs (which is my DbContext) that describes all my tables fields inside the OnModelCreating method. I also have 3 partial classes (RhAff.cs, RhEmp.cs and RhEve.cs) that also describes their respective fields.
Now I don't know how to use my stored procedures. It seems that I can use the MapToStoredProcedures but from my understanding I can only redefine insert, update and delete queries.
How can I call a select stored procedure for my models? Or any stored procedure in particular? When I was using EF Designer, I would simply right click on a table in my edmx file and would select 'Update from database', I would choose which stored procedure I wanted and was able to use them after.
You can do that as shown below.
Note: This is just an example.
SP
CREATE procedure [dbo].[CountOfOrders]
#ProductId int
AS
SELECT Count(*) From Orders o
INNER JOIN OrderDetails od ON od.OrderID = o.OrderID
WHERE od.ProductID = #ProductId
How to call it :
SqlParameter param1 = new SqlParameter("#ProductID", 72);
var totalOrders = await context.Database.SqlQuery<int>("CountOfOrders #ProductID", param1).SingleAsync();
Please read Entity Framework Code First and Stored Procedures article.

Entity Framework 4.1 - select Many to Many Association

I use Entity Framwork 4.1 and MVC 3. My question is about Join tables in Entity Framework.
I created three tables
User - UserId, Username
Role - Role Id, Rolename
UserInRoles- UserId, RoleId
I pulled these tables to my edmx file,
Only two tables appear i.e. the User and Role with a Many to Many Association between two.
If I want to get a user's role from UserInRoles table, What is the approach?
I did something like
var result = (from ar in roles
from au in users
where au.UserName == username
select new {});
This is not working. Please help.
As you guessed, the Entity Framework does combine simple look up tables like that into the parent tables in an effort to help you out. You won't be able to access the look up table in your code, but it will do the heavy lifting and allow you to navigate through the tables like such.
var result = (from ar in roles
where ar.Users.UserName == username
select ar);
Or if you prefer lambdas (personal preference):
var result = context.roles.Where(x => x.Users.UserName == username);
They should be linked I suppose:
var result =
from au in users
where au.UserName == username
select au.Roles;
Not sure if it will give you an empty collection by default. The Roles collection may have to be manually fetched. (Possibly result.Fetch(), but I'm not too familiar with it.)
(Or do you wat access to the actual UserInRole items that are stored in the database?)
Entity framework automatically generates a many to many relationship in the model, when there is only a relationshiptable with one shared primarykey that are foreign keys to other tables.
You can either add another column to this table to add it to your model or generate another unique key for the relationship.
Read more about this here :
http://learnentityframework.com/LearnEntityFramework/tutorials/many-to-many-relationships-in-the-entity-data-model/

Entity Framework - Where Clause

Let's say i have a table named User.
When I use the Entity Framework to get the records i do like this:
var db = new Context();
var users = db.Users;
It return all the users in my table. OK. If i do this:
var fooUsers = db.Users.Where(u => u.Name == 'foo');
It will give me all the users with name 'foo'. OK. My question is:
The entity framework make a query like:
select * from user where name = 'foo'
Or it load all the users and filter them on the server with lambda expression?
The Sql submitted to your database will contain your where clause. You can use SQL Server Profiler to watch as queries are submitted to your DB.
Entity Framework will translate such a query into a "Store Expression." That is, it will generate a database query -- assuming your data storage is a database -- that will be somewhat similar to the query you included in your question. It very well may name the columns, however, and there are likely to be some other differences.
From here http://msdn.microsoft.com/en-us/library/cc853327.aspx
When you create an ObjectQuery or LINQ query, the query may not be executed immediately. Query execution is deferred until the results are needed, such as during a foreach (C#) or For Each (Visual Basic) enumeration or when it is assigned to fill a List collection. Query execution begins immediately when you call the Execute method on an ObjectQuery or when you call a LINQ method that returns a singleton query, such as First or Any. For more information, see Object Queries and Query Execution (LINQ to Entities).
So when your query has a WHERE clause it will just load the results filtered by the database with the where.

Nhibernate -- Excuting some simple HQL

I have map the entities in .hmb.xml and define attribute for all entity in classes.
I have some basic accomplishment and get all the record using below code.
public List<DevelopmentStep> getDevelopmentSteps()
{
List<DevelopmentStep> developmentStep;
developmentStep = Repository.FindAll<DevelopmentStep>(new OrderBy("Id", Order.Asc));
return developmentStep;
}
I have check from net that we can write HQL, Now the problem is how to execute this HQL like..
string hql = "From DevelopmentSteps d inner join table2 t2 d.id=t2.Id where d.id=IDValue";
What additional Classes or other thing I need to add to execute this kind of HQL?
Please help me ---- Thanks
To write dynamic queries, I recommend using the Criteria API. This is dynamic, because you have a single query for several different types and you also want to set the ordering dynamically.
The queries are always object oriented. You don't need to join by foreign keys, you just navigate through the class model. There also no "tables" in the queries, but entities.
Getting (single) instances by ID should always be done using session.Get (or session.Load). Only then NHibernate can also take it directly from the cache without database roundtrip, it it had already been loaded.
for instance:
public IList<T> GetAll<T>(string orderBy)
{
return session.CreateCriteria(typeof(T))
.AddOrder(Order.Asc(orderBy))
.List<T>();
}

LINQ to SQL for tables across databases. Or View?

I have a Message table and a User table. Both are in separate databases. There is a userID in the Message table that is used to join to the User table to find things like userName.
How can I create this in LINQ to SQL? I can't seem to do a cross database join.
Should I create a View in the database and use that instead? Will that work? What will happen to CRUD against it? E.g. if I delete a message - surely it won't delete the user? I'd imagine it would throw an error.
What to do? I can't move the tables into the same database!
A view will work, if you have granted access to both database to the configured user. You'll need to use the 2-dot notation. This will only work BTW if both databases are on the same server.
create view vwUserMessages as
select * from db1.dbo.Users as users
inner join db2.dbo.Messages as msg on msg.UserID = users.id
For CRUD: a view is (usualy) only for reading: do updates etc directly to the related tables, or use a stored procedure:
create proc pdeleteUserMessages (#UserID int) as
begin trans
delete db2.dbo.Messages where userid = #UserID
delete db1.dbo.Users where id = #UserID
commit trans
go

Resources