ASP NET MVC5 Web应用程序,E.F.6,Visual Studio 2015
CategoryTrans模型类是Category模型类中的虚拟ICollection。
类别模型类是Product model类中的虚拟属性。
public partial class Product
{
public int? ID { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public virtual Category Category { get; set; }
}
public partial class Category
{
public int ID { get; set; }
public string Name { get; set; }
public int? ParentID { get; set; }
public bool IsDeleted { get; set; }
public virtual ICollection<Product> Products { get; set; }
public virtual ICollection<CategoryTrans> CategoryTrans { get; set; }
}
public class CategoryTrans
{
[Key, Column(Order = 1)]
public int category_id { get; set; }
[Key, Column(Order = 2)]
public int language_id { get; set; }
[ForeignKey("category_id")]
public virtual Category categoryId { get; set; }
[ForeignKey("language_id")]
public virtual ISO_Languages languageId { get; set; }
public string name { get; set; }
}
CategoryTrans具有由Category和ISO_languages FK制作的复合PK。在查询表格并使用产品和相关类别翻译填充productviewmodel时,我会获得所有类别的翻译(一个'category_id'以及Product.Category.CategoryTrans集合中的所有'language_id'。
我需要做的是根据用户文化输入参数过滤单个翻译(CategoryTrans.name)。
我认为可以通过将ViewModel属性设置为:
来完成public CategoryTrans CategoryTrans
{
get
{
HttpUtilities HttpHelper = new HttpUtilities();
string culture = HttpHelper.getShortCulture();
var CT = Product.Category.CategoryTrans.Select(x => new CategoryTrans
{
name = x.name
})
.Where(b => b.language_id.Equals(culture)).FirstOrDefault();
return CT;
}
而且,在视图中:
@Html.DisplayFor(modelItem => item.CategoryTrans.name)
但是当我看到CategoryTrans ICollection被正确填充时,它会一直返回空值。 我试图做一些不可能的事情,还是只是一个错误的语法问题?
答案 0 :(得分:0)
你在select中忘记了language_id。但您仍然可以优化查询。
public CategoryTrans CategoryTrans
{
get
{
HttpUtilities HttpHelper = new HttpUtilities();
string culture = HttpHelper.getShortCulture();
var CT = Product.Category.CategoryTrans
.FirstOrDefault(b => b.languageId.Equals(culture));
return CT;
}
}
答案 1 :(得分:0)
我最终通过添加
解决了这个问题 [NotMapped]
public virtual string LocalizedCategoryName { get; set; }
到产品型号类,负责显示本地化的类别名称,并设置两个嵌套的foreach循环,返回一个新的完全本地化产品列表:
private List<Product> _LocalizedProductList = new List<Product>();
public List<Product> LocalizedProductList
{
get
{
HttpUtilities HttpHelper = new HttpUtilities();
string culture = HttpHelper.getFullCulture();
int IsoCode = GenericUtilities.getIsoID(culture, db);
List<Product> localized = new List<Product>();
foreach (Product p in _LocalizedProductList)
{
foreach (CategoryTrans c in p.Category.CategoryTrans)
{
if (c.language_id.Equals(IsoCode))
{
Product x = new Product
{
ID = p.ID,
LocalizedCategoryName = c.name,
DateCreated = p.DateCreated,
DateExpire = p.DateExpire,
DateLastModified = p.DateLastModified,
Name = p.Name,
Description = p.Description,
IsApproved = p.IsApproved,
IsDeleted = p.IsDeleted,
ProductImages = p.ProductImages,
User = p.User
};
localized.Add(x);
};
}
}
return localized;
}
set { _LocalizedProductList = value; }
}
不知道它是最佳还是唯一的方式,但按预期工作。