我正在使用一个多对多数据库,其中包含通过外键连接主数据表的连接表。
http://img12.imageshack.us/img12/6500/databasew.png
对于我的数据表示,需要将多行从属表字段(例如 Genres.name)连接到数据绑定(bind)网格的一个单元格中。
书名 |流派
一些书 |小说;恐怖;谜团
对于数据集,我为此目的使用了带有 GROUP_CONCAT 的 SQL 查询:
SELECT Books.ID, Books.BOOKTITLE, GROUP_CONCAT(Genres.name, '; ') As Gen
FROM Books INNER JOIN
Books_Genres ON Books.ID = Books_Genres.book_id INNER JOIN
Genres ON Books_Genres.genre_id =Genres.id
GROUP BY Books.ID
因为我现在正在转向 EF4 并且对它还很陌生,所以我不知道如何实现可以在带有实体的数据网格中显示的相同结果表。应该对实体模型进行什么样的更改才能获得相同的结果?
非常感谢任何帮助!
更新:
我有一个由数据库生成的实体模型(Model1.edmx 和 Model1.Designer.cs)。我需要编辑 Model1.edmx(xml 文件)吗?一些循序渐进的说明会大有帮助。我刚刚开始使用 EF4,这对我来说完全是希腊语。 :)
我做了一个自定义类:
public partial class Book {
[EdmScalarProperty(EntityKeyProperty = false, IsNullable = true)]
[DataMember()]
public global::System.String GenresConcatenated
{
get { return string.Join("; ", Genres.Select(g => g.name));}
set {}
}
private List<Genre> Genres{ get; set; }
}
现在我可以在 IDE IntelliSense 中访问属性 GenresConcatenated,但是当我运行应用程序时它会抛出错误:
The number of members in the conceptual type 'MyNamespace.Book' does not match with the number of members on the object side type 'MyNamespace.Common.Book'. Make sure the number of members are the same.
看起来像:
... EntityDataSource does not support custom properties in the partial classes. It only returns the entity that is in the model. (Binding custom property in Entity Framework)
所以我回到原点。 :)
最佳答案
怎么样,
class Book
{
public int ID { get; set; }
public string Title { get; set; }
public List<Genre> Genres { get; set; }
public string Gen
{
get
{
return string.Join("; ", Genres.Select(g => g.Name));
}
}
}
然后绑定(bind)到 Book.Gen(或任何你想命名的名称)
关于c# - 替代 Group_Concat 以自定义现有 Entity Framework 模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9167756/