【发布时间】:2020-01-14 20:23:17
【问题描述】:
我的数据库中有一个 Product 表。此外,我的数据库中有品牌和类别表,它们彼此不相关。我想把这些联系起来。当我单击其中一个类别时,在表单 UI 中,应该出现他们在相关类别中拥有产品的品牌。
我试过这种方式来做到这一点。首先,我使用 GetList 方法按 categoryID 获取我的产品,然后获取这些产品的品牌,并将这些品牌添加到 pblist 列表(品牌类型)中。但是,有些产品具有相同的品牌,并且 pblist 具有重复的品牌名称。我试图用 contains 方法解决这个问题,但它不起作用。另外,我在另一部分也有同样的问题,我试图从 blist(所有品牌的列表)中删除 pblist 中未包含的品牌。我尝试通过使用以下代码获取其索引来从 blist 中删除项目: blist.RemoveAt(blist.IndexOf(item));但这一个也不起作用。它返回-1。但是项目在 blist 中。
public class BrandVM : BaseVM
{
public int ProductCount { get; set; }
}
public class BaseVM
{
public int ID { get; set; }
public string Name { get; set; }
public override string ToString()
{
return this.Name;
}
public class BrandService : ServiceBase, IBrandService
{
public List<BrandVM> GetList(int Count)
{
try
{
var result = GetQuery();
result = Count > 0 ? result.Take(Count) : result;
return result.ToList();
}
catch (Exception ex)
{
return null;
}
}
public List<BrandVM> GetListByCatID(int pCatID)
{
var plist = productService.GetListByCatID(pCatID);
List<BrandVM> pblist = new List<BrandVM>();
foreach (var item in plist)
{
if (!pblist.Contains(item.Brand))
{
pblist.Add(item.Brand);
}
};
var blist = GetList(0);
var blistBackup = GetList(0);
foreach (BrandVM item in blistBackup)
{
if (!pblist.Contains(item))
{
blist.Remove(item);
}
};
return blist;
}
这些是我与品牌相关的课程。在 BrandService 中,我分享了填充方法,还有更多方法可以填充。
这是我的 ProductService 中的方法: 我使用该方法按 CategoryID (plist) 拉产品列表
public List<ProductVM> GetListByCatID(int EntityID)
{
try
{
var result = GetQuery().Where(x => x.Category.ID==EntityID);
return result.ToList();
}
catch (Exception ex)
{
return null;
}
}
这个GetQuery方法是针对ProductService的,在其他服务中有一些区别,但也有相似之处
private IQueryable<ProductVM> GetQuery()
{
return from p in DB.Products
select new ProductVM
{
ID = p.ProductID,
Name = p.ProductName,
UnitPrice = (decimal)p.UnitPrice,
Category =p.CategoryID==null?null:new CategoryVM()
{
ID = (int)p.CategoryID,
Name = p.Category.CategoryName
},
Brand = p.BrandID == null ? null :
new BrandVM
{
ID=(int)p.BrandID,
Name=p.Brand.BrandName,
}
};
}
【问题讨论】:
-
如果你能分享minimal reproducible example,那就太棒了。请确保它是一段代码,我可以将其复制并粘贴到控制台应用程序中并按原样运行。请务必在代码中指定输入,并清楚预期的输出是什么。
-
是我的实体框架介绍项目。解决方案中有许多相互连接的类和项目。我认为,要运行这部分代码,我应该分享项目的完整解决方案。
-
@ÖdülÖngören 查看链接问题中的最佳答案。您需要在
BrandVM类中覆盖Equals()和GetHashCode()。 -
@ÖdülÖngören 或者不要按对象进行比较,而是按描述进行比较。即使用
item.Brand.Name进行比较。