开发者

entity not created problem

开发者 https://www.devze.com 2023-02-06 19:54 出处:网络
I have this class: public partial class User { private MyEntities _entities; public User() { } public User(MyEntities entities)

I have this class:

public partial class User
{
    private MyEntities _entities;

    public User()
    {
    }

    public User(MyEntities entities)
    {
        _entities = entities;
    }

    public IEnumerable<User> GetUsersRegisteredNewsletter()
    {
        return (from u in _entities.Users
                where u.Subscribe_Newsletter == true
                select u);
    }

    public IEnumerable<CallTimeOption> GetUserCallTimeOptions
    { 
        get
        {
            //_entities = new LighthouseEntities();   
            // if we uncomment the line above it works     

            var query = from a in _entities.Users.Include("CallTimeOptions")
                        where a.Id == this.Id
                        && a.CallTimeOptions.Any()
                        select a.CallTimeOptions; 

            return query.SelectMany(i => i);

        }

    }
 }

}

Now when I call GetUserCallTimeOptions it throws an error "Object reference not set to an instance of an object"

    MyEntities _entities 开发者_如何学编程= new MyEntities();
    User user = new User(_entities);
    IEnumerable<User> u = user.GetUsersRegisteredNewsletter();

    foreach (var a in u)
    {

             foreach (var y in user.GetUserCallTimeOptions)
                Response.Write(y.Text);
    }

but if I uncomment this line on GetUserCAllTimeOptions then it works:

_entities = new LighthouseEntities(); 

Shouldn't this work without the need of creating the _entities again?


You method GetUsersRegisteredNewsletter() returns instances of User that were created with the default constructor, which does not initialize _entities.

EDIT: A probably better way to do all this would be to not hold a MyEntities instance within User at all, and also to create the MyEntities with a "using" clause:

using (MyEntities entities = new MyEntities()) {
   // .... do everything, use only the above declared variable 'entities'
}
0

精彩评论

暂无评论...
验证码 换一张
取 消