Combine two or more table into one object - c#

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

Related

Linq how to use a subSelect as a virtual table in FROM

There may be similar questions out here but none that I could find for doing a subSelect in the FROM clause as a virtual table.
Most of the columns I need are in one table. There are a few columns needed from different tables that I cannot join on without getting a Cartesian join.
Here is my SQL query:
SELECT meter_name, a.loc_id, a.loc_name, a.facility_name, meter_type
FROM meter_table, (SELECT loc_id, loc_name, facility_name
FROM facility_table
WHERE id = 101) a
WHERE meter_id = a.fac_id
I have no idea how to convert this into Linq and it must be done tonight for a demo in the morning.
Assume this represents your meter_table within your database
in this case each element of the list represents a record in the database table holding the appropriate attributes
i.e the table columns will become the properties of each object
List<Meter> meter_table = new List<Meter>();
Assume this represents the facility_table table you want to join with.
same goes here, each element of the list represents a record in the database table holding the appropriate attributes
i.e the table columns will become the properties of each object
List<Facility> facility_table = new List<Facility>();
then perform the inner join like so:
var query = from m in meter_table
join a in facility_table on m.meter_id equals a.fac_id
where a.id == 101
select new { meter_name = m.MeterName,
loc_id = a.LocId,
facility_name = a.FacilityName,
meter_type = m.MeterType
};
where m.MeterName, a.LocId, a.FacilityName, m.MeterType are properties of their respective types.
it's also worth noting the variable query references an IEnumerable of anonymous types. However, if you want to return an IEnumerable of strongly typed objects then feel free to define your own type with the appropriate properties then just change select new to:
select new typeName { /* assign values appropriately */}
of the above query.

Outerjoin with a table of foreign keys in EF Data-first approach

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();

Linq to Sql - Manual association with manual parameter

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)

Create Linq Obect Based On Another Linq Object

I am using Linq to SQL in Linqpad to get to some data.
I have 3 tables I need to use to do the following steps:
1) Select customers by postcode (Customer table)
2) Get all transaction ID's for these customers (Transaction table)
3) Get itemized items for all transaxction ID's (Itemized table)
So i start out easy enough and grab the customers:
string pc = "123";
var cust =
from c in Customers
where c.PostCode.StartsWith(pc) == true
select c;
Now I need to create a new Linq object that has the lookup from transaction table based on the "CustomerID" field but I am not sure how to do this. Ive experimented with some foreach loops but cant get syntax right. Did some googling and saw posts saying not to use foreach loops with linq objects as you should use inbuilt Linq functionality but I couldnt find any examples doing what I needed.
I apologise for such a basic question but I have just started using Linq.
How do I create the next Linq object with all transaction records based on the CustoomerID field?
You can use single query with joins. If you have navigation properties in your entities:
from c in Customers
from t in c.Transactions
from i in t.ItemizedItems
where c.PostCode.StartsWith(pc)
select i
Labda syntax:
Customers.Where(c => c.PostCode.StartsWith(pc))
.SelectMany(c => c.Transactions)
.SelectMany(t => t.ItemizedItems);
If you don't have navigation properties:
from c in Customers
join t in Transactions on c.ID equals t.CustomerID
join i in t.ItemizedItems on t.ID equals i.TransactionID
where c.PostCode.StartsWith(pc)
select i

Updating multiple tables at the same time in Linq-to-SQL

How do I update two tables at the same time using Linq-to-SQL?
var z = from a in db.Products
join b in db.ProductSubcategories on
a.ProductSubcategoryID equals b.ProductSubcategoryID
join d in db.ProductCategories on
b.ProductCategoryID equals d.ProductCategoryID
select new { ProductName = a.Name, ProductCategory = d.Name,
ProductSubCategory = b.Name, Cost = a.StandardCost,
discontinuedDate = a.DiscontinuedDate,
ProductId=a.ProductID };
You have to update individual records from each table and then execute db.SubmitChanges();
In your query the output is an anonymous type, not a table type connected to the db context.
If you think in terms of SQL, linq2sql works pretty much the same. You can select a record set with a join, but you cannot update directly on this. You need to break it up and modify entries directly on Products, ProductCategories and ProductSubCategories, which equals the tables in your database.
If you want to modify a Product in Products then you have to modify the properties of that type, and not the anonymous type (joined type).

Categories