简体   繁体   中英

Linq-to-SQL - multiple tables

Really basic LINQ question but can someone enlighten me as to how it handles data when it's taken from multiple database tables.

For example if you have a Products tables then using the DBML you get a nice Product object which you can query, update, create etc. ( Product.Name , Product.Price etc.) All very nice.

However, if I have a LINQ query that joins Product on a bunch of other tables and brings me back the columns from those tables. There's no 1:1 mapping of DB table to object possible so what is it returned as?

Eg. If it was a combo of Product and Customer how would I query, for example, the customer name:

object.customerName ?

Is it returned as a dataset by default?

You would generally (that's: often, but not always.) compose anonymous types which your query will return a collection of. You name the properties, say, and can then access them as you would with any other type.

It creates what's called an 'anonymous type'. You can use it like this:

var x = from p in context.Products
        join o in OrderLines in p.Id = o.ItemId
        select new    // you are creating your anonymous type here
        {
            OrderId = o.Id,
            ProductName = p.Name,
            OrderDate = o.Date
        }

foreach (var y in x)
{
    Console.WriteLine("Product name: " + y.ProductName);
}

If your keys are set up properly, you should be able to do queries like Product.Customers or the other way around. Or you can join two tables, the syntax is similar to this:

from p in context.Products
join c in context.Customers on p.CId equals c.Id

You would generally have anonymous type or custom object depending upon the select clause of your query

from p in context.Products
join //with other tables with appropriate join conditions
select new
{
   prop1 = p.ProductName,
   prop2 = p.ProductId
}

This would return an anonymous type with 2 properties prop1 & prop2

from p in context.Products
join //with other tables with appropriate join conditions
select new MyProduct()
{
   prop1 = p.ProductName,
   prop2 = p.ProductId
}

This would return custom object called MyProduct & you can set its properties in object initializer's block

您可以在数据库中创建一个View,通过Linq-to-SQL可以映射到Object。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM