我正在尝试Catalog
使用流利的 linq 获取当前未映射到购物车的所有对象。映射表cart_catalog_mapping
由 EF 生成。我使用以下域对象。
购物车(删除了与问题无关的评论和额外字段
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; }
}
目录(再次删除了与问题无关的评论和额外字段)
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 首先创建购物车和目录表。它还识别出 Cart 具有列表并创建一个 cart_catalog_mapping 表。我正在尝试获取Catalog
表中没有引用的所有行cart_catalog_mapping
。我设想的 SQL 是
SELECT * FROM Catalog WHERE Catalog.Id NOT IN (SELECT Catalog_Id FROM cart_catalog_mapping)
我尝试使用的流利的 linq 如下: 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();
}
不幸的是,返回的 IList 没有元素。(目前 cart 或 cart_catalog_mapping 表中没有行,catalog 表中有 3 行)
差点忘了,映射表
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);
}
}