实体没有创造问题

时间:2011-01-23 15:46:34

标签: .net linq entity-framework

我有这堂课:

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

        }

    }
 }

}

现在,当我调用GetUserCallTimeOptions时,它会抛出错误“对象引用未设置为对象的实例”

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

但如果我在GetUserCAllTimeOptions上取消注释这一行,那么它可以工作:

_entities = new LighthouseEntities(); 

如果不需要再次创建_entities,这不应该工作吗?

1 个答案:

答案 0 :(得分:1)

您的方法GetUsersRegisteredNewsletter()返回使用默认构造函数创建的User实例,该构造函数不初始化_entities。

编辑:执行所有这些操作的更好方法可能是根本不在用户中保存MyEntities实例,也可以使用“using”子句创建MyEntities:

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