简体   繁体   中英

Entity Framework Joining Three Tables and Using Group Concat

I have three models like followings,

    public class Team
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }
    public class Document
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Type { get; set; }
        public string Application { get; set; }
        public ICollection<DocumentResponsible> DocumentResponsibles { get; set; }
        public string Pcda { get; set; }
        public DateTime CreatedAt { get; set; }
        public DateTime UpdatedAt { get; set; }
    }
    public class DocumentResponsible
    {
        public int Id { get; set; }
        public int DocumentId { get; set; }
        public int TeamId { get; set; }
    }

I want to write an entity framework expression to join three table and select all fields of document table and team names in one row per documents. So basicly I want to join three table use group_concat for team names. Then I want to bind it to a gridview in web form.

What I have tried,

(from dc in DBContext.Document
join dr in DBContext.DocumentResponsible on dc.Id equals dr.DocumentId
join t in DBContext.Team on dr.TeamId equals t.Id
select new
{
    Name = dc.Name,
    Type = dc.Type,
    Application = dc.Application,
    Pcda = dc.Pcda,
}).ToList();

and I have just tried it,

var data = DBContext.Dcoument.Include("DocumentResponsibles").Tolist();

It's hard to help without your DbContext and the Entity Mappings, but I'll go out on a limb saying you might just want to mark Document.DocumentResponsibles as virtual.

Also, in DocumentResponsible , maybe you'd want to add a property for Document and one for Team (both marked as virtual too) this way you don't have to do the join keys all the time you want to work with your data, EF would do it for you once properly configured.

If it doesn't work, can you add the following information to your question: First, the context class and the mappings you have. Second, if you do var firstDocument = yoneylemDB.Document.First() , how does firstDocument looks like? Does it have all it's fields and properties filled out? Is there anything weird?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM