I’m trying to get all the Catalog objects that currently aren’t mapped to a cart using fluent linq. The mapping table cart_catalog_mapping is generated by EF. I use the following domain objects.
Cart (removed comments and extra fields that aren’t pertinent to the question
public partial class Cart : BaseEntity, ILocalizedEntity
{
public virtual string Name { get; set; }
public virtual DateTime OpeningDateUtc { get; set; }
public virtual DateTime ClosingDateUtc { get; set; }
public virtual bool IsReadonly { get; set; }
public virtual bool IsPreviewMode { get; set; }
public virtual CustomerRole CustomerType { get; set; }
public virtual ICollection<Catalog> Catalogs { get; set; }
}
Catalog (again removed comments and extra fields that aren’t pertinent to the question)
public partial class Catalog : BaseEntity, ILocalizedEntity
{
public virtual string Name { get; set; }
public virtual string Code { get; set; }
public virtual bool Published { get; set; }
public virtual int DisplayOrder { get; set; }
}
EF5 w/ code first creates the Cart and Catalog table. It also recognizes that the Cart has the list and creates a cart_catalog_mapping table.
I’m trying to get all the rows in the Catalog table that don’t have a reference in the cart_catalog_mapping table. The SQL I’m envisioning is
SELECT * FROM Catalog WHERE Catalog.Id NOT IN (SELECT Catalog_Id FROM cart_catalog_mapping)
The fluent linq I’ve tried to use to get these is the following:
public IList GetAllUnassociatedCatalogs() {
IRepository _catalogRepository;
IRepository _cartRepository;
var query = from catalog in _catalogRepository.Table
from cart in _cartRepository.Table
where !cart.Catalogs.Contains(catalog)
select catalog;
return query.ToList();
}
Unfortunately the returned IList has no elements. (There are currently no rows in the cart or cart_catalog_mapping tables and 3 rows in the catalog table)
Almost forgot, the mapping tables
public partial class CartMap : EntityTypeConfiguration<Cart>
{
public CartMap()
{
this.ToTable("Cart");
this.HasKey(c => c.Id);
this.Property(c => c.Name).IsRequired().HasMaxLength(100);
this.Property(c => c.IsOnline).IsRequired();
this.HasMany(c => c.Catalogs)
.WithMany()
.Map(m => m.ToTable("Cart_Catalog_Mapping"));
}
}
public partial class CatalogMap : EntityTypeConfiguration<Catalog>
{
public CatalogMap()
{
this.ToTable("Catalog");
this.HasKey(c => c.Id);
this.Property(c => c.Name).IsRequired().HasMaxLength(100);
}
}
I’m assuming that Cart and Catalog are a many-to-many, from your example. In which case, could you not also put an ICollection of Carts on the Catalog object? If you can do that then all you’d need to do is:
Or, if you prefer without using extension methods, you can do it as @hvd suggested.