Initializing strongly typed objects in LINQ to Entities

前端 未结 5 1453
别跟我提以往
别跟我提以往 2020-12-16 01:40

I have a plain old CLR object which is essentially a wrapper for two entity framework objects, I\'m doing this so I can pass this wrapper object to a strongly typed view in

相关标签:
5条回答
  • 2020-12-16 01:56

    IF you add a parameterless constructor to your FooWrapper and then use object initialization instead, like so:

    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;
    }
    
    0 讨论(0)
  • 2020-12-16 02:01

    I found this useful what possible workarounds are there for "only parameterless constructors are support in Linq to Entites"

    0 讨论(0)
  • 2020-12-16 02:02

    Why aren't you using the .AsEnumerable()? In that way, you won't need to create a parameterless constructor and that is what you want.

    Your code was almost good. Change it to this:

    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;
    }
    

    I had the same problem today. I had a class with one parameter constructor. This constructor filled a private readonly field which was returned by a property only with a get and not with a set.

    0 讨论(0)
  • 2020-12-16 02:06

    Try a different initialization:

    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;
    }
    
    0 讨论(0)
  • 2020-12-16 02:13

    Ok, but what if you want FooObject and BarObject to be readonly? It seems a bit backwards to me that they negate the ability to use a constructor on the object.

    I can see a lot of people breaking good encapsulation practices in order to utilize object initialization in this scenario.

    0 讨论(0)
提交回复
热议问题