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.
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;
I have the following tables in my database:
SageAccount
ID (bigint)
LegacyID (nvarchar)
Customer (bit)
Consignments
ID (bigint)
Customer (nvarchar)
What I want to do is have a navigation property/association in my Linq to Sql dbml from Consignment to SageAccount. The difficulty with this is that not only do we need to match SageAccount.LegacyID => Consignments.Customer but we also need to only join to sage accounts where SageAccount.Customer is TRUE. So on the Consignments end, it isn't joining onto a field but instead a static value.
Is this possible in Linq to Sql? Note this database doesn't (and unfortunately can't) have any foreign keys setup in the database.
Yes it is possible. linq have join method. You can use it ike this in your situation:
var res = from sageAccount in _context.SageAccount
join consignments in _context.Consignments
on
new
{
LegacyID = sageAccount.LegacyID,
Customer = sageAccount.Customer
}
equals
new
{
LegacyID = consignments.ID,
Customer = true
}
select new { SageAccountID = sageAccount.ID };
Note that Property name, Type and order in the anonymous objects that you're joining on must match.
You can't use OR and AND in joins - use just equals one object to other.
This will have a this kind of result in your SQL:
SELECT [t0].[ID] AS [SageAccountID]
FROM [dbo].[SageAccount] AS [t0]
INNER JOIN [dbo].[Consignments] AS [t1] ON (([t0].[LegacyID]) = [t1].[ID])
AND ([t0].[Customer] = 1)
I need to combine two or more table into one object by using C# 4,0... I wrote a class for a table which included simple select selectbyid insert update and update.... it works fine for single table... by the way I have two attribute which specifies table name column name and primarykey... by using all these I can create my simple methods but I need to select and update more table in one object or method... what should I do or what would you suggest about it...
Example:
users and customer table I have foreign keys which defined...
If you`re using linq to sql, you can join the other tables like
var q =
from s in db.Suppliers
join c in db.Customers on s.City equals c.City
select new {
Supplier = s.CompanyName,
Customer = c.CompanyName,
City = c.City
};
as just copy & paste from a sample of MSDN LINQ to SQL: .NET Language-Integrated Query for Relational Data
I'm using the Linq to Entities. I've got my main table, Employee setup with a field named vendorID. Vendor ID is a foreign key into the Vendors table.
As it is right now, the Employee object does not directly expose the vendorID. Instead, I can only access it this way:
var employee = (from e in context.Employees.Include("tbl_vendors")
where e.employeeID = 1
select e).FirstOrDefault();
//this gets the vendor ID
int vendorID = employee.tbl_vendors.vendorID;
That is just fine and dandy, but it is extra work on the database because it is forcing a join where none is needed. Is there a way to get that key value without being forced to do a join to the tbl_vendors table?
Actually this is very simple you basically do this:
var tblVendorID = (from e in context.Employees
select e.tbl_vendors.ID).FirstOrDefault();
Even though this looks like you are doing a join L2E will optimize out the join.
Which you can confirm with code like this:
var results = from e in ctx.Employees
select e.tbl_vendors.ID;
var query = results as ObjectQuery<int>;
string sql = query.ToTraceString();
Hope this helps
Alex (Microsoft).
You can access the foreign key via the entity reference.
Employee employee = context.Employees.Single(e => e.employeeID == 1);
Int32 vendorID = (Int32)employee.tbl_vendorsReference.EntityKey.
EntityKeyValues[0].Value;
See MSDN for reference on the EntityReference and EntityKey classes.
Not sure about your object names here but you can grab the key from the entity key property without going to the database something like this:
var employee = (from e in context.Employees
where e.employeeID = 1
select e).FirstOrDefault();
//this gets the vendor ID
int vendorID = (int)employee.tbl_vendorsReference.EntityKey.EntityKeyValues[0].Value;