c# - 替代 Group_Concat 以自定义现有 Entity Framework 模型

标签 c# sql database entity-framework-4 group-concat

我正在使用一个多对多数据库,其中包含通过外键连接主数据表的连接表。

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/

相关文章:

MySQL查询用户的求和记录

C# 显示隐藏窗口

c# - 在 .NET Web API POST/PUT 方法中使用继承的类

mysql - 如果表存在 SQL 则删除行

mysql - MySQL准备语句-如何循环通过

sql-server - 从同一个表中选择按时间分组的多个计数

database - AngularFire2 如何创建用户(名字、姓氏、电子邮件、密码)

sql - 对所有内容进行后端(数据库端)验证是否可行?

c# - Discord.NET 获取特定 react 的 react 计数

c# - Ember.js 查找从 webapi Controller 返回的第一个数据属性的模型