English 中文(简体)
将准则中强烈分类的物体引入实体
原标题:Initializing strongly typed objects in LINQ to Entities
  • 时间:2009-09-17 17:42:12
  •  标签:

我有一个很古老的《南极海生委》物体,它基本上为两个实体框架物体的包裹,因此,我可以把这个包裹的物体带给多国师协会框架的强烈分类观点。 我的oo包裹非常简单:

public class FooWrapper
{
    public FooWrapper(Foo f, Bar b)
    {
        this.FooObject = f;
        this.BarObject = b;
    }

    public Foo FooObject { get; private set; }
    public Bar BarObject { get; private set; }
}

我迄今对我名单“FoosWith Bars”的职能如下:

public IEnumerable<FooWrapper> ListFoosWithBars(int userID)
{
    IEnumerable<Bar> tempBar = ListBarsByUserID(userID);
    IEnumerable<FooWrapper> results = (from f in _entities.FooSet
                                       join b in tempBar on f.ID equals b.foos.ID
                                       select new FooWrapper(f, b));
    return results;
}

之所以这样做,是因为显然向实体提供的LINQ不支持标准化的初始化,只是一个例外,它只是说:“对于无参数的建筑和初始化器,在LINQ至实体中得到支持。 我很想知道,是否还有其他办法实现同样的结果?

最佳回答

红十字与红新月联会在你们的FooWrapper上添加一个无参数的构件,然后使用物体初步化,如:

public IEnumerable<FooWrapper> ListFoosWithBars(int userID)
{
    IEnumerable<Bar> tempBar = ListBarsByUserID(userID);

    IEnumerable<FooWrapper> results = (
        from f in _entities.FooSet
        join b in tempBar on f.ID equals b.foos.ID
        select new FooWrapper()
        {
            FooObject = f, 
            BarObject = b
        });

    return results;
}
问题回答

奥基,但是如果你想要只读法吗? 对我来说,他们否定了在物体上使用建筑商的能力,这似乎只是一个倒退。

我可以看到很多人打破了良好的资本做法,以便在这一情景中利用最初的反对。

为什么不使用。 这样,你们就不需要创建无足轻重的建筑,这是你们想要的。

你的法典几乎是好的。 为此:

public IEnumerable<FooWrapper> ListFoosWithBars(int userID)
{
    IEnumerable<Bar> tempBar = ListBarsByUserID(userID);
    IEnumerable<FooWrapper> results = (from f in _entities.FooSet.AsEnumerable()
                                       join b in tempBar on f.ID equals b.foos.ID
                                       select new FooWrapper(f, b));
    return results;
}

我今天也存在同样的问题。 我有一个等级,有一个参数构造。 该建筑商只填充了私人阅读的田地,只用一个 get子而不是一个 set子归还一个财产。

1. 不同的初始化:

public class FooWrapper
{
    public FooWrapper() { }

    public Foo FooObject { get; set; }
    public Bar BarObject { get; set; }
}


public IEnumerable<FooWrapper> ListFoosWithBars(int userID)
{
    IEnumerable<Bar> tempBar = ListBarsByUserID(userID);

    IEnumerable<FooWrapper> results = (
        from f in _entities.FooSet
        join b in tempBar on f.ID equals b.foos.ID
        select new FooWrapper 
        {
            FooObject = f,
            BarObject = b
        });

    return results;
}




相关问题
热门标签