Domanda

Scenario:

As mentioned here, once you add additional properties to a simple join table (many-to-many relationship), it's no longer a hidden association. These questions also address this:

The existing code already uses the simple, automatically hidden navigation properties, and there are some minor customizations to the autogenerated tables, and so I'd like to avoid refactoring the entire project when I alter the underlying relationship table.

Question:

Is there a way so that both the automatic navigation (many-to-many) accessors can remain, but I can also access the relationship entity directly?

I could just write my own accessors selecting from the relationship table, but then they're no longer EntityCollections and thus I'm concerned that I lose whatever magic happens under the hood like tracking, etc.

Can I manually add EntityCollections to entities?

Expectation:

Originally: Product* <-> *Offer

  • a Product has many Offers (like 50% off, BOGO)
  • the same Offer could apply to many Products ("Red Shirt" and "Blue Pants" are BOGO)

Desired: Product* <-[sort]-> *Offer

  • When I list Offers for a Product, I can sort them independently
  • i.e. "Red Shirt" has "50% off" then "BOGO", but "Blue Pants" shows "BOGO" then "50% off"

then I would want to be able to do:

// original access, do stuff
List<Offer> applicableOffers = currentProduct.Offers.Where(...);
// hit up the join table directly for properties
var applicableOffersInOrder = applicableOffers.OrderBy(o => o.ProductOffers.Sort);

rather than

var applicableOffersInOrder = currentProduct.ProductOffers
        .OrderBy(o => o.Sort)
        .Offers.Where(...);
È stato utile?

Soluzione

I think the easiest way to do it is simply add two properties manually in a non-autogenerated partial class:

partial class Offer
{
    public IQueryable<Product> Products 
    { 
       get { return this.ProductOffers.Select(x => x.Product); } 
    }
}
partial class Product
{
    public IQueryable<Offer> Offers 
    { 
       get { return this.ProductOffers.OrderBy(x => x.Sort).Select(x => x.Offer); } 
    }
}

This won't help for when you want to add a new ProductOffer, but since you actually have extra data (Sort) you should be doing that via the ProductOffers collection anyway.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top