none
Can't get data from DomainContext in code

    Question

  • Пока начинал делать свое приложение и настраивал привязки, то все данные нормально извлекались и отображались в элементах DataGrid и других, но как только решил программно извлечь данные, то столкнулся с проблемой, что данные не извлекаются.
    [code=csharp]var ctx = new DatabaseContext();
    gridUsers.ItemsSource = ctx.tblUsers;
    ctx.Load(ctx.GetTblUsersQuery());
    Пробовал делать это несколькими способами, но ничего не получилось
    [code=csharp]var ctx = new DatabaseContext();
    EntityQuery<tblUser> query = ctx.GetTblUsersQuery();
    LoadOperation<tblUser> operation = ctx.Load(query);
    foreach (var item in operation.Entities)
    {
        listBox1.Items.Add(item.LastName);
    }
    [code=csharp]var ctx = new DatabaseContext();
    ctx.Load(ctx.GetTblUsersQuery());
    foreach (var item in ctx.tblUsers)
    {
        listBox1.Items.Add(item.LastName);
    }
    После выполнения этих функций, объект ctx.tblUsers оказывается пустым и данные не извлекаются.
    Может я забыл что-то настроить? Во многих примерах такие методики работают.
    Также непонятно с запись данных, делаю так
    [code=csharp]foreach (var item in CurrentTestLog.Questions)
    {
    tblResultItem ResultItem = new tblResultItem();
    ResultItem.QuestionID = item.QuestionID;
    ResultItem.AnswerID = item.AnswerID;
    ResultItem.IsRight = item.IsRight;
    db.tblResultItems.Add(ResultItem);
    }
    db.SubmitChanges();
    Когда выполнился этот цикл, то добавилась только первая запись с ID=0 (ключевое поле), больше я ничего не смог добавить в БД.
    Как вообще сделать, чтобы ID (ключевое поле) автоматически прописывался? У меня база SQL Server была преобразована из Access и может не все там правильно настроилось.

    I have an application on Silverlight (Silverlight 4 + ASP.NET) with EntityFramework database and with DomainContext service.

    When i'm trying to get data in C# code, I get an empty data. But when i'm binding this DB, data gets well. Where i'm wrong?

    Binding:

    var ctx = new DatabaseContext();
    gridUsers.ItemsSource = ctx.tblUsers;
    ctx.Load(ctx.GetTblUsersQuery());


    getting data in code

    var ctx = new DatabaseContext();
    EntityQuery<tblUser> query = ctx.GetTblUsersQuery();
    LoadOperation<tblUser> operation = ctx.Load(query);
    
    foreach (var item in operation.Entities)
    {
        listBox1.Items.Add(item.LastName);
    }

    2nd method

    var ctx = new DatabaseContext();
    ctx.Load(ctx.GetTblUsersQuery());
    
    foreach (var item in ctx.tblUsers)
    {
        listBox1.Items.Add(item.LastName);
    }
    But ctx.tblUsers always empty :(

    Thursday, June 30, 2011 8:51 AM

Answers

  • Hi,

    Forgot callback function so that too late.

    e.g

    01.private ObservableCollection<Order> _orders;

    02.public ObservableCollection<Order> Orders
    03.{
    04. get {return _orders;}
    05. private set
    06. {
    07. _orders = Order;
    08. RaisePropertyChanged("Order");
    09. }
    10.}
    11.
    12.public void LoadOrders()
    13.{
    14. this.Context.Load(Context.GetOrdersQuery(), LoadOrdersCompleted, null);
    15.}
    16.
    17.private void LoadOrdersCompleted(LoadOperation<Order> lo)
    18.{
    19. Orders = new ObservableCollection<Order>(Context.Orders);
    20.}

    Thursday, June 30, 2011 8:57 AM
  • Ravenger, I just looked at your code and the answer is still the same. The Load is asynchronous, you will not be able to loop thorugh it until the load completes. Thaicarrot's code was correct but you are not using it.

    You are calling the load and then immediatly trying to foreach through the results. The results are always going to be empty at that point in your app.

    Thursday, June 30, 2011 1:53 PM
  • return this.ObjectContext.tblQuestions.Include("tblAnswer");

    That should be .Include("tblAnswers");

    Friday, July 01, 2011 10:59 AM

All replies

  • Hi,

    Forgot callback function so that too late.

    e.g

    01.private ObservableCollection<Order> _orders;

    02.public ObservableCollection<Order> Orders
    03.{
    04. get {return _orders;}
    05. private set
    06. {
    07. _orders = Order;
    08. RaisePropertyChanged("Order");
    09. }
    10.}
    11.
    12.public void LoadOrders()
    13.{
    14. this.Context.Load(Context.GetOrdersQuery(), LoadOrdersCompleted, null);
    15.}
    16.
    17.private void LoadOrdersCompleted(LoadOperation<Order> lo)
    18.{
    19. Orders = new ObservableCollection<Order>(Context.Orders);
    20.}

    Thursday, June 30, 2011 8:57 AM
  • But when i'm binding this DB, data gets well. Where i'm wrong?

    You did everything right, but Binding is support asychronous binding so that it is work.

    Thursday, June 30, 2011 9:18 AM
  • I'm adapted your code, but it still not work


    public class LoadUsers
    {
        DatabaseContext ctx = new DatabaseContext();
    
        private ObservableCollection<tblUser> _users;
        public ObservableCollection<tblUser> Users
        {
            get
            {
                return _users;
            }
            private set
            {
                _users = Users;
                RaisePropertyChanged("Users"); //Error: Cannot resolve symbol.
            }
        }
    
        public LoadUsers()
        {
            ctx.Load(ctx.GetTblUsersQuery(), LoadUsersCompleted, null);
        }
    
        private void LoadUsersCompleted(LoadOperation<tblUser> lo)
        {
            Users = new ObservableCollection<tblUser>(ctx.tblUsers);
        }
    }

    and


    LoadUsers data = new LoadUsers();
    foreach (var item in data.Users)
    {
          listBox1.Items.Add(item.LastName);
    }
    Thursday, June 30, 2011 9:42 AM
  • If that is not ViewModel just like following


    public class LoadUsers
    {
        DatabaseContext ctx = new DatabaseContext();
    
        private ObservableCollection<tblUser> _users;
        public ObservableCollection<tblUser> Users {get; private set;}
        {
            get
            {
                return _users;
            }
            private set
            {
                _users = Users;
                RaisePropertyChanged("Users"); //Error: Cannot resolve symbol.
            }
        }
    
        public LoadUsers()
        {
            ctx.Load(ctx.GetTblUsersQuery(), LoadUsersCompleted, null);
        }
    
        private void LoadUsersCompleted(LoadOperation<tblUser> lo)
        {
            Users = new ObservableCollection<tblUser>(ctx.tblUsers);
        }
    }

    and


    LoadUsers data = new LoadUsers();
    foreach (var item in data.Users)
    {
          listBox1.Items.Add(item.LastName);
    }

     

    Thursday, June 30, 2011 9:55 AM
  • You construct your LoadUsers class which creates a new DomainContext and starts a load. You then immediatly attempt to access the loaded data. Since the load hasn't completed yet (in fact, may not have even been sent to the server yet) you can't access the data. Wrapping the Context inside a class doesn't get you anything, the load is still asynchronous.

    Thursday, June 30, 2011 9:56 AM
  • I'm rewrite my code and putted the Context outside, but Users property still empty


    static DatabaseContext ctx = new DatabaseContext();
    public class LoadUsers
    {
        public ObservableCollection<tblUser> Users { get; private set; }
    
        public LoadUsers()
        {
            ctx.Load(ctx.GetTblUsersQuery(), LoadUsersCompleted, null);
        }
    
        private void LoadUsersCompleted(LoadOperation<tblUser> lo)
        {
            Users = new ObservableCollection<tblUser>(ctx.tblUsers);
        }
    }
    Thursday, June 30, 2011 10:07 AM
  • The code was right may be the problem is PC's cache. Right click your solution "Clean "

    Try create new simple SL project. Try try.

    Thursday, June 30, 2011 10:22 AM
  • I made simple silverlight app with embedded DB and was trying get data in 3 ways - DomainDataSource, standart binding and with code, but it not work :(

    I don't know how to attach file (my simple app) and i uploaded it to RapidShare

    https://rapidshare.com/files/3890221437/RIATest.rar

    Thursday, June 30, 2011 12:11 PM
  • Ravenger, I just looked at your code and the answer is still the same. The Load is asynchronous, you will not be able to loop thorugh it until the load completes. Thaicarrot's code was correct but you are not using it.

    You are calling the load and then immediatly trying to foreach through the results. The results are always going to be empty at that point in your app.

    Thursday, June 30, 2011 1:53 PM
  • It works!!! I hadn't understood meaning of asynchronous loading before.

    Thanks so much

    Thursday, June 30, 2011 3:07 PM
  • Another small problem

    I have 2 table, Question and Answers, when i'm reading data in code and getting data from Questions table, how can i get linked data from Answer table?

    Here is my tables

    Here is my code

                foreach (var item in Questions)
                {
                    var question = new QuestionInfo();
                    question.QuestionID = item.QuestionID;
                    question.QuestionText = item.Text;
                    if (item.AnswerType != null) question.AnswerType = (AnswerType)item.AnswerType;
                    if (item.Difficulty != null) question.QuestionDifficulty = (int)item.Difficulty;
                    foreach (var answeritem in item.tblAnswers)    //item.tblAnswers always empty           {
                        var answer = new AnswerInfo();
                        answer.AnswerID = answeritem.AnswerID;
                        answer.AnswerText = answeritem.Text;
                        if (answeritem.IsTrue != null) answer.AnswerTrue = (bool)answeritem.IsTrue;
                    }
    
                    CurrentTest.Questions.Add(question);
                }

    I'm added some code to DomainService, but this doesn't work

    public IQueryable<tblQuestion> GetTblQuestions()
    {
       return this.ObjectContext.tblQuestions.Include("tblAnswer");
    }
    ============================================
        public partial class tblQuestion
        {
            internal sealed class tblQuestionMetadata
            {
                private tblQuestionMetadata()  { }
    
                //some properties
    
                [Include]
                public EntityCollection<tblAnswer> tblAnswers { get; set; }
            }
        }
    Friday, July 01, 2011 7:59 AM
  • return this.ObjectContext.tblQuestions.Include("tblAnswer");

    That should be .Include("tblAnswers");

    Friday, July 01, 2011 10:59 AM
  • Hello, i have a similar problem. I looked your code and i made next steps in my application:

    1. Add new class LoadProfiles in client part of my application:

    2. and use class LoadProfiles:

    public class LoadProfiles
        {
            public ProfileDomainContext ctx;
            public ObservableCollection<Table_Profiles> Profiles { get; private set; }
            public LoadProfiles(ProfileDomainContext context)
            {
                ctx = context;
                ctx.Load(ctx.GetTable_ProfilesQuery(), LoadProfilesCompleted, null);
            }
    
            private void LoadProfilesCompleted(LoadOperation<Table_Profiles> lo)
            {
                Profiles = new ObservableCollection<Table_Profiles>(ctx.Table_Profiles);
            }
        }
    private void button1_Click(object sender, System.Windows.RoutedEventArgs e)
    {
             LoadProfiles data = new LoadProfiles((ProfileDomainContext)this.profileDomainDataSource.DomainContext);
    
             foreach (var item in data.Profiles)
             {
                  textBox1.Text = item.name;
             }
    }
    
    
    But it does not work (error NullReferenceException). Can you help me?
    Monday, April 09, 2012 2:26 PM