I have a table Admins, which creates a relationship between Users and Locations:
ID - numeric (PK)
UserId - uniqueidentifier (FK to UserId in aspnet_Users table)
LocationId - numeric
Now I want to execute command:
IQueryable<decimal> location_ids = (from m in _db.Admins
where m.UserId.Equals( new Guid("c5d3dc0e-81e6-4d6b-a9c3-faa802e10b7d")) && m.LocationId.Equals(conf.umisteni.Budova.ID)
select m.LocationId);
But for some reason (I guess the UsersId is FK) m.UserId can't be resolved. So I tried to use
m.aspnet_UsersReference.Value.UserId
But then the decision statement
if (!location_ids.Any())
fails with exception
System.NotSupportedException: The specified type member 'aspnet_UsersReference' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported.
What should I do in order to get the enumerable list of LocationIds?
Thanks in advance.
You're missing a 'Users' and a dot:
var location_ids = (from m in _db.Admins
where m.Users.UserId.Equals(
new Guid("c5d3dc0e-81e6-4d6b-a9c3-faa802e10b7d")) &&
m.LocationId.Equals(conf.umisteni.Budova.ID)
select m.LocationId);
Essentially, you need to use the relationship "Users" directly.
Related
I have a table Users which contain user information. I have a table Products which contain product information. I have a table called UserProduct which acts as a junction table and whose fields are UserId and ProductId. I am using a Entity Framework database first approach.
I want to outerjoin using Linq to find the following data.
All Users in the Users table.
All Users who have bought a particular product in terms of a Boolean called isPurchased.
My thinking was to left outer join table User with UserProduct and get all users and whether they have a product something like this.
var result = from a in Users
join b in UserProduct(Not available through EF) on a.Id equals b.prodId into group1
from g1 in group1.DefaultIfEmpty()
select new
{
id = g1.Id,
isPurchased = g1.prodId != null
}.ToList();
However in EF mapping, the object UserProduct is not created and so I cannot use it directly in my Linq query? So how do I go about this? Is there a way I can use linq to join tables with the actual table name(UserProduct) instead of joining entities?
Assuming Users contains a property List<Products> products to represent the junction information, and a variable boughtProductId to represent the particular product:
var result = from u in Users
let isPurchased = u.products.Any(p => p.Id == boughtProductId)
select new {
id = isPurchased ? boughtProductId : null,
isPurchased
}.ToList();
I have a question about foreign keys in a database. I am programming in c#, using the Entity framework (visual studio winforms) and I have data in my sql database with foreign keys.
I have queries which access these data to get them in a Datagrid. Everything is OK, except I have data in tables which are foreign keys (numbers). When I select them with queries I only get the foreign key (a number) and not the value which is linked in another table.
var requete_reservations = from reservation_spa in bdd.reservation_spa
where reservation_spa.NOMBRE_RESERVATION > 0
select new
{
reservation_spa.CLIENT,
reservation_spa.SPA,
reservation_spa.NOMBRE_RESERVATION
};
dataGrid_reservations.DataSource = requete_reservations.ToList();
In reservation_spa.client I have a number which links another table client
How can I get the Name from client using the foreign keys in reservation_spa?
You must Join table reservation_spa and Client like this :
var requete_reservations = from r in bdd.reservation_spa
join c in bdd.client on r.CLIENT equals c.IDCLIENT
where r.NOMBRE_RESERVATION > 0
select new
{
c.NOM,
r.SPA,
r.NOMBRE_RESERVATION
};
Where is the name for? If you just need the name you could use linq
var name= from c in bdd.Clients //Is that the name of the table of clients?
where c.IDClient= requete_reservations.Client
select c;
For this kind of schema:
mainTable(Id,Name) //Id is primary key
secondryTable(mainTableId,RegDate,Age) // mainTableId is foreign key
Can anyone give me a example of Linq to Sql using navigation properites.
With join I am selecting as:
from mainT in db.mainTable
join secT in db.secondryTable on mainT.Id equals secT.mainTableId
select new { mainT.Name, secT.RegDate, secTable.Age}
I found a solution on my own :) The query would be:
FROM mainT in db.mainTable
SELECT new
{
mainT.Name,
regDate = mainT.secT.Where(//some condition),
age = mainT.secT.Where(//some condition)
}
The above query is valid only if the Primary key/Foreign key relationships are defined properly in database.
In brief: is there any difference between fetching records using lambda expression vs using query expression?
In below example:
I fetched one employee record
Modified his salary Without saving
changes to context I fetch same record with Salary table included
Why are the results different when doing query 2 vs query 3?
var empdId = Guid.Parse("C8475622-09A9-4284-80D4-AAXXK");
//City for this employee was Washington in database
var emp = ctx.Employee
.FirstOrDefault(emp => emp.ID == empId);
emp.City = "New York"; //Modified the entity
//Lambda version
//Fetched again including foreign key relation Salary
var employeeCity = ctx.Employee.Include("Salary")
.FirstOrDefault(emp => emp.ID == empdId).City;
//New York
var cityfetchedAgain = from e in ctx.Employee
join sal in ctx.Salary on e.ID equals sal.EmployeeId
where e.ID == empdId
select e.City;
var city = cityfetchedAgain.FirstOrDefault();
//Washington
EDIT:
I will re-phrase my question: Include version of query returns the changed property, even if the changes are not committed to database. However LINQ Join is not aware of changes in the context (City property here). Records were fetched from database.
I have explicit foreign key configured between these tables. Should I
always prefer Include?
I seem to have trouble adding objects to tables that have a 'n to n' relationship.
Tables are defined as follows:
Table A
ID (PRIMARY)
...
...
...
Table B
ID (PRIMARY)
...
...
...
Table C
TableA_ID (index)
TableB_ID (index)
So basically Table C links Table A and B, by their IDs. Using the entity framework we now have an object TableA containing an Entity Collection of TableB entities.
However when I add an existing object of type TableB to the TableA.TableBs entity collection property, I receive an exception:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '(SELECT\n TableC.TableA, \n ' at line 1
It seems that I'm trying to do a very normal / common thing, however I've not been successful getting this to work.
C# code:
var database = new DatabaseEntities();
var tableAObject = database.SingleOrDefault(e => e.ID == 1);
var tableBObject = database.SingleOrDefault(e => e.ID == 1);
tableA.TableBEntities.Add(tableBObject);
database.SaveChanges();
Apparently I'm doing something wrong, so my question is, how should I add an object to Table C?