从联接返回合并实体

时间:2015-04-02 12:20:59

标签: c# .net entity-framework model-view-controller

是否可以返回单个对象,该对象由使用EF6的两个实体之间的连接组成?

这是我的意思的一个例子,但是,我不知道使用什么类型,选择或返回以获得组合数据集...所以我用????表示了那些??在示例中。

    public static ?????? GetAppDetails(AppsLight item)
    {
        using (ApplicationEntities db = new ApplicationEntities())
        {
            ?????? retval = (from t in db.Applications
                             join g in db.Licenses on t.LicenseID equals g.LicenseID
                             where t.AppID == item.UID
                             select ????).FirstOrDefault();

            return retval;

        }
    }

2 个答案:

答案 0 :(得分:1)

您应该创建自己的类型以返回。

public class MyReturnType
{
    public Application App { get; set; }
    public License License { get; set; }
}


public static MyReturnType GetAppDetails(AppsLight item)
{
    using (ApplicationEntities db = new ApplicationEntities())
    {
        var retval = (from t in db.Applications
                         join g in db.Licenses on t.LicenseID equals g.LicenseID
                         where t.AppID == item.UID
                         select new MyReturnType
                         {
                            App = t,
                            License = l
                         }).FirstOrDefault();
        return retVal;
    }
}

如果您已正确配置外键,则不需要进行显式连接,并且可以执行此类操作。

public static Application GetAppDetails(AppsLight item)
{
    using (ApplicationEntities db = new ApplicationEntities())
    {

        var application = (from t in db.Applications
                         where t.AppID == item.UID
                         select new MyReturnType)
             .Include(x => x.License)
             .FirstOrDefault();

        //application should have a .License property. 
        return application;
    }
}

如果您不想创建新类型,也可以使用Tuple

public static Tuple<Application, License> GetAppDetails(AppsLight item)
{
    using (ApplicationEntities db = new ApplicationEntities())
    {
        var tuple = (from t in db.Applications
                         join g in db.Licenses on t.LicenseID equals g.LicenseID
                         where t.AppID == item.UID
                         select Tuple.Create(t, l))
                     .FirstOrDefault();
        return tuple;
        //access the items in the tuple like this: tuple.Item1; tuple.Item2;
    }
}

答案 1 :(得分:0)

  public static CombinedDto GetAppDetails(AppsLight item)
{
    using (ApplicationEntities db = new ApplicationEntities())
    {
        CombinedDto retval = (from t in db.Applications
                         join g in db.Licenses on t.LicenseID equals g.LicenseID
                         where t.AppID == item.UID
                         select(b=>new CombinedDto { ApplicationId = t, LicenceId = item})).FirstOrDefault();

        return retval;

    }
}
publi class CombinedDto()
{
  public Application Application {get;set;}
  public Licence Licence {get;set;}
}

使用dto或anonymus对象。我认为会更好。 谢谢。