【问题标题】:Subsonic 3 - SimpleRepository亚音速 3 - SimpleRepository
【发布时间】:2010-11-13 16:17:17
【问题描述】:

我正在玩 Subsonic 3 的简单存储库,并且在理解如何处理外键方面遇到了困难......

如果我有一个产品对象包含

int ID; 

string name; 

string description; 

Category category; 

int categoryID (this one is just to persist the product's categoryID to the DB)

and a category object containing 

int ID; 

string name;

我如何使用存储库来返回所有产品的列表以及它们的类别对象实例化?

目前我已经编写了一个连接 product.categoryID = category.ID 的 linq 查询,这一切都很好,但是当我 .ToList() 这个查询的结果时,产品的 Category 没有被实例化。

有没有办法做到这一点,还是我必须为每个产品手动实例化类别?

谢谢,

保罗

【问题讨论】:

    标签: c# .net subsonic subsonic3 repository


    【解决方案1】:

    您需要获取 linq 来填充它,
    使用类似
    var query = from product in repo.All(Product)
    在 repo.All(Category) 中加入 categoryItem
    在 product.CategoryId 上等于 categoryItem.Id
    选择新的 {
    ID = 产品.ID,
    名称 = 产品名称,
    描述 = 产品描述,
    categoryId= 产品.CategoryId
    类别 = 类别项目
    };

    【讨论】:

    • 这听起来像是答案...今晚会尝试然后让你知道伙计干杯人
    • 嗨,波奇,感谢您的帮助。为了将其重铸为产品列表,我是否必须手动遍历列表并为每个结果实例化一个新产品对象(当前为 [匿名类型] 类型)
    • 我知道没有简单的方法,除了按照你说的手动分配它。匿名类型在 C# 中是只读的。另一种选择是单独加载类别并遍历产品。您可以缓存 Category 表,然后只访问数据库一次。抱歉,这不是您想要的答案。
    • 类似这样的 List prods = repo.All().ToList(); List categories = (from product in repo.All() join category in repo.All() on product.categoryId 等于 category.Id select category).Distinct().ToList(); foreach(产品 prods 中的产品 prod){ prod.category = categories.Find(c => c.Id == prod.categoryId ); }
    • TheVillageIdiot,你真的应该创建一个新的问题线程。无论如何,你得到什么错误信息?还有你有什么版本的亚音速?波奇
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多