【问题标题】:Include Child Entity Collection in Silverlight Domain Service在 Silverlight 域服务中包含子实体集合
【发布时间】:2012-01-27 06:07:11
【问题描述】:

我有一个域服务类如下

[MetadataTypeAttribute(typeof(Question.QuestionMetadata))]
public partial class Question
{     
    internal sealed class QuestionMetadata
    {
        private QuestionMetadata()
        {
        }

        [Include]
        public EntityCollection<Answer> Answers { get; set; }

        public EntityCollection<AssignmentsQuestionsMapping> AssignmentsQuestionsMappings { get; set; }

        public int Marks { get; set; }

        public string QuestionDescription { get; set; }

        public long QuestionID { get; set; }

        public string QuestionTitle { get; set; }

        public EntityCollection<UserQuestionAnsweredMapping> UserQuestionAnsweredMappings { get; set; }
    }
}

我在域服务中有以下查询

public IQueryable<Question> GetQuestionsByAssignmentId(long assignmentId)
        {
            var questions = from q in this.ObjectContext.Questions.Include("Answers")
                            join qam in this.ObjectContext.AssignmentsQuestionsMappings on q.QuestionID equals qam.QuestionID
                            join assign in this.ObjectContext.Assignments on qam.AssignmentID equals assign.AssignmentID
                            where assign.AssignmentID == assignmentId
                            select q;

            return questions;
        }

据我所知,如果您想在域服务查询中包含子实体,那么您可以在实体的元数据文件中设置 [Include] 属性,并通过 .Include("ChildEntityCollectionName") 将其包含在查询中。

我已经完成了这两项工作,但我仍然没有在我的客户端收到 ChildEntity Collection。 我错过了什么??

【问题讨论】:

  • 您在数据库中的问题和答案之间设置了外键吗?如果是这样,您的模型 (ConceptualEntityModel) 自实施以来是否已更新?
  • yes 答案表有问题 ID 作为伪造键。奇怪的是,当我返回 this.ObjectContext.Questions.Include("Answers") 即在查询中没有 linq 时,我确实在客户端的 Question 实体中获得了 Answers 实体。任何想法发生了什么??
  • 您能否直接在 SQL 中运行相同的查询并验证您是否获得了结果?您需要验证数据库中的数据是否符合您在 LINQ 中的假设。
  • 我确实在数据库上运行了查询,它为我提供了结果。同样正如我之前所说,我得到了问题列表,但没有得到我试图包含的问题中的答案。

标签: entity-framework silverlight-4.0 include wcf-ria-services


【解决方案1】:

你快到了。您需要添加关联属性以帮助 WCF RIA 了解 QuestionAnswer 之间的关系。

[Include]
[Association("Question_Answer", "QuestionID", "ParentQuestionID", IsForeginKey=false)]
public EntityCollection<Answer> Answers { get; set; }

这假设您的实体共享一个外键。

public class Question
{
...
    [Key]
    public long QuestionID { get; set;}
...
}

public class Answer
{
...
    [Key]
    public long AnswerID { get; set;}

    public long ParentQuestionID { get; set;}
...
}

您可以通过RIA Services: Inserting multiple presentation-model objects查看更多信息

【讨论】:

  • 我认为如果您的数据库中存在关联,则无需在代码中提供显式关联。此外,奇怪的是当我返回 this.ObjectContext.Questions.Include("Answers") 即在查询中没有 linq 时,我确实在客户端的 Question 实体中获得了 Answers 实体。任何想法发生了什么??
猜你喜欢
  • 2022-06-10
  • 1970-01-01
  • 1970-01-01
  • 2011-01-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-20
  • 2022-01-19
相关资源
最近更新 更多