简体   繁体   中英

Entity Framework Relationships Not Returning All Results

I already deleted the .edmx and recreated it multiple times!

Issue is that only some of the ProductAttributes (and only for some products and not all) are returning on the following code:

   var p = context.Products.FirstOrDefault(x => x.ProductNumber.Equals(productSku));x.ProductNumber.Equals(productSku));
            foreach (var attr in p.ProductAttributes)
            {
              //only prints some results
            }

Where as the follow works fine:

   var p = context.Products.FirstOrDefault(x => x.ProductNumber.Equals(productSku));
            var pAttrs = context.ProductAttributes.Where(x => x.ProductNumber.Equals(productSku));
            foreach (var attr in pAttrs)
            {
               //prints all of the results
            }

To ensure that I set the relationships correct here are some screen shots:

在此处输入图片说明

在此处输入图片说明 在此处输入图片说明

EDIT:

I did delete a product or two from ProductAttribute who did not have a product, I initally realized that there was no consistency after a database migration. So I attempted to clean the data by eliminating the ProductAttributes with no products. Then put the relationship into play with check existing data set to yes.

I currently just ran the follow queries for both tables. ProductAttribute and Product,

  SELECT t1.name
FROM table1 t1
LEFT JOIN table2 t2 ON t2.name = t1.name
WHERE t2.name IS NULL

To find (if T1 is productAttribute) if there are any ProductAttributes with no ProductNumber reference in Product Table. And return 0 rows as result. I assume that means that the ProductAttribute Table has no ProductNumbers that do not appear in Product.

Include ProductAttributes in Product

Add below reference

using System.Data.Entity

And

var p = context.Products.Include(p => p.ProductAttributes).FirstOrDefault(x => x.ProductNumber.Equals(productSku));

Edit

This may be you have deleted some products and didn't delete productattributes or somehow there is inconsistancy in database. so you must set insert and update specific to Cascade

This will delete ProductAttributes of one product if you delete that product

If you are using EF:

EF by default is using lazy binding, the ProductAttributes will not be retrieved from Database until you explicitly specify that. So try this:

var p = context.Products.Include(x => x.ProductAttributes).FirstOrDefault(x => x.ProductNumber.Equals(productSku));
foreach (var attr in p.ProductAttributes)
{
    // This should print out all data
}

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