LINQ to SQL Table Dependency

If I have two tables ... Category and Pet.

Is there a way in LINQ to SQL to make the result of a merged query map to another strongly typed class (for example: PetWithCategoryName) so that I can pass it to MVC View?

I currently have categories and pet classes ... should I do another one?

Maybe I missed something. Can any of you enlighten me?

from p in petTable
join c in categoryTable on p.CategoryId equals c.Id
where (c.Id == categoryId.Value)
select new
{
    p.Id, 
    p.Name,
    p.Description,
    p.Price,
    CategoryName = c.Name
}

<?xml version="1.0" encoding="utf-8" ?>
<Database Name="PetShop" xmlns="http://schemas.microsoft.com/linqtosql/mapping/2007">
  <Table Name="Category" Member="PetShop.Models.Category">
    <Type Name="PetShop.Models.Category">
      <Column Name="Id" Member="Id" IsDbGenerated="true" IsPrimaryKey="true" />
      <Column Name="Name" Member="Name" />
      <Column Name="Description" Member="Description" />
    </Type>
  </Table>
  <Table Name="Pet" Member="PetShop.Models.Pet">
    <Type Name="PetShop.Models.Pet">
      <Column Name="Id" Member="Id" IsDbGenerated="true" IsPrimaryKey="true" />
      <Column Name="Name" Member="Name" />
      <Column Name="Description" Member="Description" />
      <Column Name="ImageUrl" Member="ImageUrl" />
      <Column Name="Price" Member="Price" />
      <Column Name="CategoryId" Member="CategoryId" />
      <Association Name="FK_Pet_Category" Member="Category" ThisKey="CategoryId" OtherKey="Id" IsForeignKey="true" />
    </Type>
  </Table>
</Database>
+3
source share
2 answers

How can i use loadwith? I do not find much help on the Internet. Any good resources?

I found this online: http://blogs.msdn.com/wriju/archive/2007/10/04/linq-to-sql-change-in-datacontext-from-beta-1-to-beta-2.aspx

You would do something like:

var loadOption = new DataLoadOptions();           
loadOption.LoadWith<Pets>(p => p.Category);
db.LoadOptions = loadOption; 

var pets = from p in PetStoreContext.Pets
           select p;

, .

+4

LoadWith LoadOption, Pet ,

MyPet.Category.Name, , Pet.

Linq To SQL, .

+1

Source: https://habr.com/ru/post/1698029/


All Articles