Simple Linq-to-entities query involving .Include I believe

杀马特。学长 韩版系。学妹 提交于 2019-12-13 06:21:45

问题


I have a Linq-to-Entities query that is not complicated but requires an .include and/or projection and/or join because it must be executed in one pass.

Here is my database (Microsoft SQL Server 2008):

Table A (Customers) (contains CustomerID (customer IDs), and ZipCode (zip codes) as strings.

Table C (Categories) (contains CategoryID (categories) like "food", "shelter","clothing", "housing" (primary keys).

Table A_C is a linking table, since Tables A and C are linked as many-to-many: contains just two fields: CustomerID "customer IDs" and CategoryID (Categories), in combination as primary keys. This table is a linking table betweeen tables A and C.

Here is my query, that must be executed in just one trip to the database: I need to select all records in Table A that satisfy a condition, then filter these records depending on a 'list of parameters' that are found in the linking Table A_C--and do this all in one trip to the database. But I don't know what the length or composition of the list of parameters for Table A_C is, ahead of time--it varies from call to call. Thus this list of parameters varies method call by method call.

To give a more concrete example:

Table A has a list of customer IDs. I find the customers that live in a certain Zip code. Then, in the same SQL query, I need to find which of these customers have selected certain categories: Food, Clothing, Housing, etc, but my web method does not know ahead of time what these categories are, rather, they are passed as a list to the method: List myCategoryList (which could be 1 category or 100 categories, and varies method call by method call).

How do I write the projection using Linq-to-Entities? When the list of parameters varies? And do it all in one pass?

  List<string> CategoryList = new List<string>() { "Food", "Shelter", "Housing" }; // in one call to the web service method

   List<string> CategoryList = new List<string>() { "Food", "Clothing" }; //could be a second call--it varies and I don't know ahead of time what the List will be

So how can I do the SQL query using Linq-to-Entities? In one pass? (Of course I could loop through the list, and make repeated trips to the database, but that's not an optimal solution I am told). Projection,.Include are keywords but surfing the net yielded nothing.

Here is a crude guess, just to get ball rolling:

 public void WebMethod1 (CategoryList)
 {

 using (EntityFramework1 context = new EntityFramework1())

 {
  /* assume CategoryList is a list of strings passed into the method and is,for     this      particular call,something like:  List<string> CategoryList = new List<string>() { "Food", "Clothing" }; for this call,      but in the next call it could be: List<string> CategoryList = new List<string>() { "Food", "Shelter", "Housing" } */

 string ZipCodeString = "12345";
 string customerIDString = "E12RJ55";

 var CustomersFromZipCodeHavingSelectedCertainCategories =  from x in context.A_C
                            where x.A.CustomerID == customerIDString
                            where x.A.StartsWith(ZipCodeString)
                            where x.A_C.Contains(CategoryList) //???? This is clearly not grammatical, but what is?
                            select x;

 }

/*

my problem is: I want to filter all records from A that contain a zipcode 12345, and that also have a certain CustomerID "E12RJ55" from table A, but further filter this set with all such CustomerIDs in linking table A_C that contain the categories "Food" and "Clothing".

How to do this in one pass? I can do this quite easily in multiple passes and trips to the database using code, but somebody in this thread here http://bit.ly/rEG2AM suggested I do a Join/projection and do it all in one fell swoop.

*/

I will also accept SQL answers since it might help yield a solution. This question btw is not difficult I believe--but I could not find an answer on the net.

EDIT: with answer and credit to david s. I thank you for the answer david.s. Here is what worked, slightly different than the answer by david.s, in that I am using the linking table (bridge table) called “Customer_Categories” that is between the table Customer and Categories and contains the primary key of each (as is required for many-to-many relationships). This bridge table is what I called "A_C" in my original answer, and here has ints rather than strings but is the same thing. Intellisense picked up this table and I used it, and it works. Also keep in mind that CategoryList is a list of ints, List CategoryList = new List();, yet amazingly it automagically works inside this SQL-to-Entities query:

Var CustomersFromZipCOde = context.Customers.Where (custo => custo.CustomerID==customerIDString && custo.ZipCode.StartsWith(ZipCodeString) && custo.Customer_Categories.Any(categ => CategoryList.Contains(categ.CategoryID)));

//gives the right output, incredible.

回答1:


First of all i would like to say that even if you explanation is very long it is not very clear. You would like a simple Linq-to-Entities query but you don't give the Entities, you only speak of tables in your database.

Assuming you have the following entities:

public class Customer
{
    public string CustomerID { get; set; }
    public string ZipCode { get; set; }
    public virtual ICollection<Category> Categories { get; set; }
}

public class Category
{
    public string CategoryID { get; set; }
    public virtual ICollection<Customer> Customers { get; set; }
}

Your query might look like this:

var CustomersFromZipCodeHavingSelectedCertainCategories =
    context.Customers.Where(
        customer => customer.CustomerID == customerIDString &&
                    customer.ZipCode.StartsWith(ZipCodeString) &&
                    customer.Categories.Any(
                        category => CategoryList.Contains(category.CategoryID));

More info on other ways to do this here: http://smehrozalam.wordpress.com/2010/06/29/entity-framework-queries-involving-many-to-many-relationship-tables/



来源:https://stackoverflow.com/questions/8202847/simple-linq-to-entities-query-involving-include-i-believe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!