Search Results

Search found 783 results on 32 pages for 'datacontext'.

Page 7/32 | < Previous Page | 3 4 5 6 7 8 9 10 11 12 13 14  | Next Page >

  • Castle Windsor Dynamic Property in XML config

    - by haxelit
    I'm trying to set the DataContext on ApplicationMainWindow which is a WPF window. When I set it up in the XML like so it leaves the DataContext null: <!-- View Models --> <component id="mainwindow.viewmodel" type="ProjectTracking.ApplicationMainViewModel, ProjectTracking" inspectionBehavior="none" lifestyle="transient"> </component> <!-- UI Components --> <component id="mainwindow.view" type="ProjectTracking.ApplicationMainWindow, ProjectTracking" inspectionBehavior="none" lifestyle="transient"> <parameters> <DataContext>${mainwindow.viewmodel}</DataContext> </parameters> </component> But if I do it this way via C# it works. _Kernel.Register( ... Component.For<ApplicationMainWindow>() .DynamicParameters( (k,d) => { d["DataContext"] = k[typeof(ApplicationMainViewModel)]; }) ); I'm instantiating my window like so: Window window = _Kernel[typeof(ApplicationMainWindow)] as Window; When I configure windsor via the xml config it leaves my DataContext NULL, but when I configure it via code it works like a charm. Do I need to use code to pull this off, or should it work via XML config ? Thanks, Raul

    Read the article

  • How do I bind to something outside a datacontext.

    - by AKRamkumar
    I have a listbox in WPF that is in the Layout Root. I also have a Frame that is in the Layout Root as well. The listbox is composed of items that have a string(Name) and a framework element(UI). How do I bind the frame's content to be the UI property of the listbox's selected item property? If you need a codebehind, how would you do this in MVVM

    Read the article

  • Can't return a List from a Compiled Query.

    - by Andrew
    I was speeding up my app by using compiled queries for queries which were getting hit over and over. I tried to implement it like this: Function Select(ByVal fk_id As Integer) As List(SomeEntity) Using db As New DataContext() db.ObjectTrackingEnabled = False Return CompiledSelect(db, fk_id) End Using End Function Shared CompiledSelect As Func(Of DataContext, Integer, List(Of SomeEntity)) = _ CompiledQuery.Compile(Function(db As DataContext, fk_id As Integer) _ (From u In db.SomeEntities _ Where u.SomeLinkedEntity.ID = fk_id _ Select u).ToList()) This did not work and I got this error message: Type : System.ArgumentNullException, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 Message : Value cannot be null. Parameter name: value However, when I changed my compiled query to return IQueryable instead of List like so: Function Select(ByVal fk_id As Integer) As List(SomeEntity) Using db As New DataContext() db.ObjectTrackingEnabled = False Return CompiledSelect(db, fk_id).ToList() End Using End Function Shared CompiledSelect As Func(Of DataContext, Integer, IQueryable(Of SomeEntity)) = _ CompiledQuery.Compile(Function(db As DataContext, fk_id As Integer) _ From u In db.SomeEntities _ Where u.SomeLinkedEntity.ID = fk_id _ Select u) It worked fine. Can anyone shed any light as to why this is? BTW, compiled queries rock! They sped up my app by a factor of 2.

    Read the article

  • How to select all parent objects into DataContext using single LINQ query ?

    - by too
    I am looking for an answer to a specific problem of fetching whole LINQ object hierarchy using single SELECT. At first I was trying to fill as much LINQ objects as possible using LoadOptions, but AFAIK this method allows only single table to be linked in one query using LoadWith. So I have invented a solution to forcibly set all parent objects of entity which of list is to be fetched, although there is a problem of multiple SELECTS going to database - a single query results in two SELECTS with the same parameters in the same LINQ context. For this question I have simplified this query to popular invoice example: public static class Extensions { public static IEnumerable<T> ForEach<T>(this IEnumerable<T> collection, Action<T> func) { foreach(var c in collection) { func(c); } return collection; } } public IEnumerable<Entry> GetResults(AppDataContext context, int CustomerId) { return ( from entry in context.Entries join invoice in context.Invoices on entry.EntryInvoiceId equals invoice.InvoiceId join period in context.Periods on invoice.InvoicePeriodId equals period.PeriodId // LEFT OUTER JOIN, store is not mandatory join store in context.Stores on entry.EntryStoreId equals store.StoreId into condStore from store in condStore.DefaultIfEmpty() where (invoice.InvoiceCustomerId = CustomerId) orderby entry.EntryPrice descending select new { Entry = entry, Invoice = invoice, Period = period, Store = store } ).ForEach(x => { x.Entry.Invoice = Invoice; x.Invoice.Period = Period; x.Entry.Store = Store; } ).Select(x => x.Entry); } When calling this function and traversing through result set, for example: var entries = GetResults(this.Context); int withoutStore = 0; foreach(var k in entries) { if(k.EntryStoreId == null) withoutStore++; } the resulting query to database looks like (single result is fetched): SELECT [t0].[EntryId], [t0].[EntryInvoiceId], [t0].[EntryStoreId], [t0].[EntryProductId], [t0].[EntryQuantity], [t0].[EntryPrice], [t1].[InvoiceId], [t1].[InvoiceCustomerId], [t1].[InvoiceDate], [t1].[InvoicePeriodId], [t2].[PeriodId], [t2].[PeriodName], [t2].[PeriodDateFrom], [t4].[StoreId], [t4].[StoreName] FROM [Entry] AS [t0] INNER JOIN [Invoice] AS [t1] ON [t0].[EntryInvoiceId] = [t1].[InvoiceId] INNER JOIN [Period] AS [t2] ON [t2].[PeriodId] = [t1].[InvoicePeriodId] LEFT OUTER JOIN ( SELECT 1 AS [test], [t3].[StoreId], [t3].[StoreName] FROM [Store] AS [t3] ) AS [t4] ON [t4].[StoreId] = ([t0].[EntryStoreId]) WHERE (([t1].[InvoiceCustomerId]) = @p0) ORDER BY [t0].[InvoicePrice] DESC -- @p0: Input Int (Size = 0; Prec = 0; Scale = 0) [186] -- Context: SqlProvider(Sql2008) Model: AttributedMetaModel Build: 3.5.30729.1 SELECT [t0].[EntryId], [t0].[EntryInvoiceId], [t0].[EntryStoreId], [t0].[EntryProductId], [t0].[EntryQuantity], [t0].[EntryPrice], [t1].[InvoiceId], [t1].[InvoiceCustomerId], [t1].[InvoiceDate], [t1].[InvoicePeriodId], [t2].[PeriodId], [t2].[PeriodName], [t2].[PeriodDateFrom], [t4].[StoreId], [t4].[StoreName] FROM [Entry] AS [t0] INNER JOIN [Invoice] AS [t1] ON [t0].[EntryInvoiceId] = [t1].[InvoiceId] INNER JOIN [Period] AS [t2] ON [t2].[PeriodId] = [t1].[InvoicePeriodId] LEFT OUTER JOIN ( SELECT 1 AS [test], [t3].[StoreId], [t3].[StoreName] FROM [Store] AS [t3] ) AS [t4] ON [t4].[StoreId] = ([t0].[EntryStoreId]) WHERE (([t1].[InvoiceCustomerId]) = @p0) ORDER BY [t0].[InvoicePrice] DESC -- @p0: Input Int (Size = 0; Prec = 0; Scale = 0) [186] -- Context: SqlProvider(Sql2008) Model: AttributedMetaModel Build: 3.5.30729.1 The question is why there are two queries and how can I fetch LINQ objects without such hacks?

    Read the article

  • EF Many-to-many dbset.Include in DAL on GenericRepository

    - by Bryant
    I can't get the QueryObjectGraph to add INCLUDE child tables if my life depended on it...what am I missing? Stuck for third day on something that should be simple :-/ DAL: public abstract class RepositoryBase<T> where T : class { private MyLPL2Context dataContext; private readonly IDbSet<T> dbset; protected RepositoryBase(IDatabaseFactory databaseFactory) { DatabaseFactory = databaseFactory; dbset = DataContext.Set<T>(); DataContext.Configuration.LazyLoadingEnabled = true; } protected IDatabaseFactory DatabaseFactory { get; private set; } protected MyLPL2Context DataContext { get { return dataContext ?? (dataContext = DatabaseFactory.Get()); } } public IQueryable<T> QueryObjectGraph(Expression<Func<T, bool>> filter, params string[] children) { foreach (var child in children) { dbset.Include(child); } return dbset.Where(filter); } ... DAL repositories public interface IBreed_TranslatedSqlRepository : ISqlRepository<Breed_Translated> { } public class Breed_TranslatedSqlRepository : RepositoryBase<Breed_Translated>, IBreed_TranslatedSqlRepository { public Breed_TranslatedSqlRepository(IDatabaseFactory databaseFactory) : base(databaseFactory) {} } BLL Repo: public IQueryable<Breed_Translated> QueryObjectGraph(Expression<Func<Breed_Translated, bool>> filter, params string[] children) { return _r.QueryObjectGraph(filter, children); } Controller: var breeds1 = _breedTranslatedRepository .QueryObjectGraph(b => b.Culture == culture, new string[] { "AnimalType_Breed" }) .ToList(); I can't get to Breed.AnimalType_Breed.AnimalTypeId ..I can drill as far as Breed.AnimalType_Breed then the intelisense expects an expression? Cues if any, DB Tables: bold is many-to-many Breed, Breed_Translated, AnimalType_Breed, AnimalType, ...

    Read the article

  • What could possibly be different between the table in a DataContext and an IQueryable<Table> when do

    - by Nate Bross
    I have a table, where I need to do a case insensitive search on a text field. If I run this query in LinqPad directly on my database, it works as expected Table.Where(tbl => tbl.Title.Contains("StringWithAnyCase") In my application, I've got a repository which exposes IQueryable objects which does some initial filtering and it looks like this var dc = new MyDataContext(); public IQueryable<Table> GetAllTables() { var ret = dc.Tables.Where(t => t.IsActive == true); return ret; } In the controller (its an MVC app) I use code like this in an attempt to mimic the LinqPad query: var rpo = new RepositoryOfTable(); var tables = rpo.GetAllTables(); // for some reason, this does a CASE SENSITIVE search which is NOT what I want. tables = tables.Where(tbl => tbl.Title.Contains("StringWithAnyCase"); return View(tables); The column is defiend as an nvarchar(50) in SQL Server 2008. Any help or guidance is greatly appreciated!

    Read the article

  • Why can't you return a List from a Compiled Query?

    - by Andrew
    I was speeding up my app by using compiled queries for queries which were getting hit over and over. I tried to implement it like this: Function Select(ByVal fk_id As Integer) As List(SomeEntity) Using db As New DataContext() db.ObjectTrackingEnabled = False Return CompiledSelect(db, fk_id) End Using End Function Shared CompiledSelect As Func(Of DataContext, Integer, List(Of SomeEntity)) = _ CompiledQuery.Compile(Function(db As DataContext, fk_id As Integer) _ (From u In db.SomeEntities _ Where u.SomeLinkedEntity.ID = fk_id _ Select u).ToList()) This did not work and I got this error message: Type : System.ArgumentNullException, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 Message : Value cannot be null. Parameter name: value However, when I changed my compiled query to return IQueryable instead of List like so: Function Select(ByVal fk_id As Integer) As List(SomeEntity) Using db As New DataContext() db.ObjectTrackingEnabled = False Return CompiledSelect(db, fk_id).ToList() End Using End Function Shared CompiledSelect As Func(Of DataContext, Integer, IQueryable(Of SomeEntity)) = _ CompiledQuery.Compile(Function(db As DataContext, fk_id As Integer) _ From u In db.SomeEntities _ Where u.SomeLinkedEntity.ID = fk_id _ Select u) It worked fine. Can anyone shed any light as to why this is? BTW, compiled queries rock! They sped up my app by a factor of 2.

    Read the article

  • Entity framework 4.0 compiled query with Where() clause issue

    - by Andrey Salnikov
    Hello, I encountered with some strange behavior of System.Data.Objects.CompiledQuery.Compile function - here is my code for compile simple query: private static readonly Func<DataContext, long, Product> productQuery = CompiledQuery.Compile((DataContext ctx, long id) => ctx.Entities.OfType<Data.Product>().Where(p => p.Id == id) .Select(p=>new Product{Id = p.Id}).SingleOrDefault()); where DataContext inherited from ObjectContext and Product is a projection of POCO Data.Product class. My data context in first run contains Data.Product {Id == 1L} and in second Data.Product {Id == 2L}. First using of compilled query productQuery(dataContext, 1L) works perfect - in result I have Product {Id == 1L} but second run productQuery(dataContext, 2L) always returns null, instead of context in second run contains single product with id == 2L. If I remove Where clause I will get correct product (with id == 2L). It seems that first id value caching while first run of productQuery, and therefore all further calls valid only when dataContext contains Data.Product {id==1L}. This issue can't be reproduced if I've used direct query instead of its precompiled version. Also, all tests I've performed on test mdf base using SQL Server 2008 express and Visual studio 2010 final from my ASP.net application.

    Read the article

  • linq to sql with nservicebus table lock issue

    - by IGoor
    I am building a system using NServiceBus and my DataLayer is using Linq 2 SQL. The system is made up of 2 services. Service1 receives messages from NSB. It will query Table1 in my database and inserts a record into Table1 If a certain condition is met a new NSB message is sent to the 2nd service Service2 will update records also in Table1 when it receives messages from Service1 and it does some other non database related work. Service2 is a long running process. The problem I am having is the moment Service2 updates a record in Table1, the table is locked. The lock seems to be in place until Service2 has completed all it is processing. i.e. The lock is not released after my datacontext is disposed. This causes the query in Service1 to timeout. Once Service2 completes processing, Service1 resumes processing again without problem. So for example Service1 code may look like: int x =0; using (DataContext db = new DataContext()) { x = (from dp in db.Table1 select dp).Count(); // this line will timeout while service2 is processing Table1 t = new Table1(); t.Data = "test"; db.Table1.InsertOnSubmit(t); db.SubmitChanges(); } if(x % 50 == 0) CallService2(); The code in service2 may look like: using (DataContext db = new DataContext()) { Table1 t = db.Table1.Where(t => t.id == myId); t.Data = "updated"; db.SubmitChanges(); } // I would have expected the lock to have been released at this point, but this is not the case. DoSomeLongRunningTasks(); // lock will be released once service2 exits I don't understand why the lock is not released when the datacontext is disposed in Service2. To get around the problem I have been calling: db.ExecuteCommand("SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED"); and this works, but I am not happy using it. I want to solve this problem properly. Has any one experienced this sort of problem before and does any one know how to solve it? Why is the lock not released after the datacontext has been disposed? Thanks in advance. p.s. sorry for the extremely long post.

    Read the article

  • What code smell best describes this code?

    - by Paul Stovell
    Suppose you have this code in a class: private DataContext _context; public Customer[] GetCustomers() { GetContext(); return _context.Customers.ToArray(); } public Order[] GetOrders() { GetContext(); return _context.Customers.ToArray(); } // For the sake of this example, a new DataContext is *required* // for every public method call private void GetContext() { if (_context != null) { _context.Dispose(); } _context = new DataContext(); } This code isn't thread-safe - if two calls to GetOrders/GetCustomers are made at the same time from different threads, they may end up using the same context, or the context could be disposed while being used. Even if this bug didn't exist, however, it still "smells" like bad code. A much better design would be for GetContext to always return a new instance of DataContext and to get rid of the private field, and to dispose of the instance when done. Changing from an inappropriate private field to a local variable feels like a better solution. I've looked over the code smell lists and can't find one that describes this. In the past I've thought of it as temporal coupling, but the Wikipedia description suggests that's not the term: Temporal coupling When two actions are bundled together into one module just because they happen to occur at the same time. This page discusses temporal coupling, but the example is the public API of a class, while my question is about the internal design. Does this smell have a name? Or is it simply "buggy code"?

    Read the article

  • WPF Combobox binding Question

    - by ebattulga
    I have a 2 Table. Product ProductName CategoryID Category ID CategoryName I'm filling combobox to table named 'category'. Code Product currentProduct=datacontext.products.FirstOrDefault(); this.datacontext=currentProduct; combobox1.Itemssource=datacontext.categories; XAML <Textbox Text="{Binding Path=ProductName}"></Textbox> <Combobox x:Name="combobox1" SelectedItem="Binding Path=CategoryID"></Combobox> When click save button, I'm doing datacontext.SubmitChanges() ProductName changed. But CategoryID not changed. My target is when i select from combobox, selected category ID set to CategoryID of currentProduct. (like currentProduct.CategoryID=(Category as combobox1.SelectedItem).ID) How to do is from xaml?

    Read the article

  • Linq to SQL case sensitivity causing problems

    - by Roger Lipscombe
    I've seen this question, but that's asking for case-insensitive comparisons when the database is case-sensitive. I'm having a problem with the exact opposite. I'm using SQL Server 2005, my database collation is set to Latin1_General_CI_AS. I've got a table, "User", like this: CREATE TABLE [dbo].[User] ( [Id] [int] IDENTITY(1,1) NOT NULL, [Name] [nvarchar](max) NOT NULL, CONSTRAINT [PK_Example] PRIMARY KEY CLUSTERED ( [Id] ASC ) ) And I'm using the following code to populate it: string[] names = new[] { "Bob", "bob", "BoB" }; using (MyDataContext dataContext = new AppCompatDataContext()) { foreach (var name in names) { string s = name; if (dataContext.Users.SingleOrDefault(u => u.Name == s) == null) dataContext.Users.InsertOnSubmit(new User { Name = name }); } dataContext.SubmitChanges(); } When I run this the first time, I end up with "Bob", "bob" and "BoB" in the table. When I run it again, I get an InvalidOperationException: "Sequence contains more than one element", because the query against the database returns all 3 rows, and... SELECT * FROM [User] WHERE Name = 'bob' ... is case-insensitive. That is: when I'm inserting rows, Linq to SQL appears to use C# case-sensitive comparisons. When I query later, Linq to SQL uses SQL Server case-insensitive comparisons. I'd like the initial insert to use case-insensitive comparisons, but when I change the code as follows... if (dataContext.Users.SingleOrDefault(u => u.Name.Equals(s, StringComparison.InvariantCultureIgnoreCase) ) == null) ... I get a NotSupportedException: "Method 'Boolean Equals(System.String, System.StringComparison)' has no supported translation to SQL." Question: how do I get the initial insert to be case-insensitive or, more precisely, match the collation of the column in the database? Update: This doesn't appear to be my problem. My problem appears to be that SingleOrDefault doesn't actually look at the pending inserts at all.

    Read the article

  • Help with linq to sql compiled query

    - by stackoverflowuser
    Hi I am trying to use compiled query for one of my linq to sql queries. This query contains 5 to 6 joins. I was able to create the compiled query but the issue I am facing is my query needs to check if the key is within a collection of keys passed as input. But compiled queries do not allow passing of collection (since collection can have varying number of items hence not allowed). For instance input to the function is a collection of keys. Say: List<Guid> InputKeys List<SomeClass> output = null; var compiledQuery = CompiledQueries.Compile<DataContext, IQueryable<SomeClass>>( (context) => from a in context.GetTable<A>() where InputKeys.Contains(a.Key) select a); using(var dataContext = new DataContext()) { output = compiledQuery(dataContext).ToList(); } return output; Is there any work around or better way to do the above?

    Read the article

  • Why can't I Bind a viewmodel property to a dependency property of a custom control

    - by Robert
    I want to use a color picker in my wpf application and I saw a nice looking one on this codeproject page. The control works fine until I want to connect the control to a viewmodel. I created a small test program with this viewmodel: public class ColorViewModel : ViewModelBase { public ColorViewModel() { LineColor = Brushes.Yellow; } SolidColorBrush _brushColor; public SolidColorBrush LineColor { get { return _brushColor; } set { _brushColor = value; RaisePropertyChanged(() => LineColor); } } } The test program has a textbox and the colorpicker controls: <StackPanel Orientation="Horizontal"> <TextBlock Text="Please Select a Color" FontWeight="Bold" Margin="10" Foreground="{Binding Path=LineColor, UpdateSourceTrigger=PropertyChanged}"/> <vw:ColorPickerControlView x:Name="ForeColorPicker" Margin="10" CurrentColor="{Binding Path=LineColor, UpdateSourceTrigger=PropertyChanged }"/> </StackPanel> In the loaded event of the window I set the viewmodel to the datacontext like this: DataContext = new ColorViewModel(); The problem is that I can't seem to bind the LineColor property of the viewmodel to the CurrentColor property of the ColorPickerControlView. The CurrentControl property of the ColorPickerControlView seems to be fine. The constructor looks like this: public ColorPickerControlView() { this.DataContext = this; InitializeComponent(); CommandBindings.Add(new CommandBinding(SelectColorCommand, SelectColorCommandExecute)); } In the constructor of the UserControl there is the line this.DataContext = this; I read that is is necessary to bind the dependency properties. Do I override this line when I set my viewmodel to the datacontext and is that why I can't bind to the CurrentColor property? Is there any workaround? Or did I make another mistake?

    Read the article

  • DataReader already open when using LINQ

    - by Jamie Dixon
    I've got a static class containing a static field which makes reference to a wrapper object of a DataContext. The DataContext is basically generated by Visual Studio when we created a dbml file & contains methods for each of the stored procedures we have in the DB. Our class basically has a bunch of static methods that fire off each of these stored proc methods & then returns an array based on a LINQ query. Example: public static TwoFieldBarData[] GetAgesReportData(string pct) { return DataContext .BreakdownOfUsersByAge(Constants.USER_MEDICAL_PROFILE_KEY, pct) .Select(x => new TwoFieldBarData(x.DisplayName, x.LeftValue, x.RightValue, x.TotalCount)) .ToArray(); } Every now and then, we get the following error: There is already an open DataReader associated with this Command which must be closed firs This is happening intermittently and I'm curious as to what is going on. My guess is that when there's some lag between one method executing and the next one firing, it's locking up the DataContext and throwing the error. Could this be a case for wrapping each of the DataContext LINQ calls in a lock(){} to obtain exclusivity to that type and ensure other requests are queued?

    Read the article

  • Linq to SQL gives NotSupportedException when using local variables

    - by zwanz0r
    It appears to me that it matters whether you use a variable to temporary store an IQueryable or not. See the simplified example below: This works: List<string> jobNames = new List<string> { "ICT" }; var ictPeops = from p in dataContext.Persons where ( from j in dataContext.Jobs where jobNames.Contains(j.Name) select j.ID).Contains(p.JobID) select p; But when I use a variable to temporary store the subquery I get an exception: List<string> jobNames = new List<string> { "ICT" }; var jobs = from j in dataContext.Jobs where jobNames.Contains(j.Name) select j.ID; var ictPeops = from p in dataContext.Persons where jobs.Contains(p.JobID) select p; "System.NotSupportedException: Queries with local collections are not supported" I don't see what the problem is. Isn't this logic that is supposed to work in LINQ?

    Read the article

  • Out of memory when creating a lot of objects C#

    - by Bas
    I'm processing 1 million records in my application, which I retrieve from a MySQL database. To do so I'm using Linq to get the records and use .Skip() and .Take() to process 250 records at a time. For each retrieved record I need to create 0 to 4 Items, which I then add to the database. So the average amount of total Items that has to be created is around 2 million. while (objects.Count != 0) { using (dataContext = new LinqToSqlContext(new DataContext())) { foreach (Object objectRecord in objects) { // Create a list of 0 - 4 Random Items and add each Item to the Object for (int i = 0; i < Random.Next(0, 4); i++) { Item item = new Item(); item.Id = Guid.NewGuid(); item.Object = objectRecord.Id; item.Created = DateTime.Now; item.Changed = DateTime.Now; dataContext.InsertOnSubmit(item); } } dataContext.SubmitChanges(); } amountToSkip += 250; objects = objectCollection.Skip(amountToSkip).Take(250).ToList(); } Now the problem arises when creating the Items. When running the application (and not even using dataContext) the memory increases consistently. It's like the items are never getting disposed. Does anyone notice what I'm doing wrong? Thanks in advance!

    Read the article

  • Entity Framework DateTime update extremely slow

    - by Phyxion
    I have this situation currently with Entity Framework: using (TestEntities dataContext = DataContext) { UserSession session = dataContext.UserSessions.FirstOrDefault(userSession => userSession.Id == SessionId); if (session != null) { session.LastAvailableDate = DateTime.Now; dataContext.SaveChanges(); } } This is all working perfect, except for the fact that it is terribly slow compared to what I expect (14 calls per second, tested with 100 iterations). When I update this record manually through this command: dataContext.Database.ExecuteSqlCommand(String.Format("update UserSession set LastAvailableDate = '{0}' where Id = '{1}'", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fffffff"), SessionId)); I get 55 calls per second, which is more than fast enough. However, when I don't update the session.LastAvailableDate but I update an integer (e.g. session.UserId) or string with Entity Framework, I get 50 calls per second, which is also more than fast enough. Only the datetime field is terrible slow. The difference of a factor 4 is unacceptable and I was wondering how I can improve this as I don't prefer using direct SQL when I can also use the Entity Framework. I'm using Entity Framework 4.3.1 (also tried 4.1).

    Read the article

  • wp7 odata v2 dataservicestate save and restore methods tombstoning example needed

    - by MIantosca
    I am looking for an example of how to use the new DataServiceState Save and Restore methods in a WP7 application in order to tombstone a datacontext - I cannot find any examples and the approach I used resulted in an exception this saves the data context correctly PhoneApplicationService.Current.State["DataContext"] = DataServiceState.Save(this.Model.Entities); this attempts to restore it after the app is re-activated var dc = (PhoneApplicationService.Current.State["DataContext"] as DataServiceState).Restore(); but throws an exception An item could not be added to the collection. When items in a DataServiceCollection are tracked by the DataServiceContext, new items cannot be added before items have been loaded into the collection. This is the same exception I get if I try to reload a datacontext that I stored "directly" (without using the DataServiceState.Save method) in the PhoneApplicationService.Current.State. I cannot find any offical documentation on the new ODATA v2 DataServiceState class or examples. thanks Michael

    Read the article

  • How to check if an entityset is populated

    - by TheQ
    How can i check if an entityset of a linq-object is populated or not? Example code below. My model have two methods, one joins data, and the other does not: public static Member GetMemberWithSettings(Guid memberId) { using (DataContext db = new DataContext()) { DataLoadOptions dataLoadOptions = new DataLoadOptions(); dataLoadOptions.LoadWith<Member>(x => x.Settings); db.LoadOptions = dataLoadOptions; var query = from x in db.Members where x.MemberId == memberId select x; return query.FirstOrDefault(); } } public static Member GetMember(Guid memberId) { using (DataContext db = new DataContext()) { var query = from x in db.Members where x.MemberId == memberId select x; return query.FirstOrDefault(); } } Then my control have the following code: Member member1 = Member.GetMemberWithSettings(memberId); Member member2 = Member.GetMember(memberId); Debug.WriteLine(member1.Settings.Count); Debug.WriteLine(member2.Settings.Count); The last line will generate a "Cannot access a disposed object" exception. I know that i can get rid of that exception just by not disposing the datacontext, but then the last line will generate a new query to the database, and i don't want that. What i would like is something like: Debug.WriteLine((member1.Settings.IsPopulated()) ? member1.Settings.Count : -1); Debug.WriteLine((member2.Settings.IsPopulated()) ? member2.Settings.Count : -1); Is it possible?

    Read the article

  • CRUD operations; do you notify whether the insert,update etc. went well ?

    - by danielovich
    Hi guys. I have a simple question for you (i hope) :) I have pretty much always used void as a "return" type when doing CRUD operations on data. Eg. Consider this code: public void Insert(IAuctionItem item) { if (item == null) { AuctionLogger.LogException(new ArgumentNullException("item is null")); } _dataStore.DataContext.AuctionItems.InsertOnSubmit((AuctionItem)item); _dataStore.DataContext.SubmitChanges(); } and then considen this code: public bool Insert(IAuctionItem item) { if (item == null) { AuctionLogger.LogException(new ArgumentNullException("item is null")); } _dataStore.DataContext.AuctionItems.InsertOnSubmit((AuctionItem)item); _dataStore.DataContext.SubmitChanges(); return true; } It actually just comes down to whether you should notify that something was inserted (and went well) or not ?

    Read the article

  • How to check if a child-object is populated

    - by TheQ
    How can i check if a child-object of a linq-object is populated or not? Example code below. My model have two methods, one joins data, and the other does not: public static Member GetMemberWithPhoto(Guid memberId) { using (DataContext db = new DataContext()) { DataLoadOptions dataLoadOptions = new DataLoadOptions(); dataLoadOptions.LoadWith<Member>(x => x.UserPhoto); db.LoadOptions = dataLoadOptions; var query = from x in db.Members where x.MemberId == memberId select x; return query.FirstOrDefault(); } } public static Member GetMember(Guid memberId) { using (DataContext db = new DataContext()) { var query = from x in db.Members where x.MemberId == memberId select x; return query.FirstOrDefault(); } } Then my control have the following code: Member member1 = Member.GetMemberWithPhoto(memberId); Member member2 = Member.GetMember(memberId); Debug.WriteLine(member1.UserPhoto.ToString()); Debug.WriteLine(member2.UserPhoto.ToString()); The last line will generate a "Cannot access a disposed object" exception. I know that i can get rid of that exception just by not disposing the datacontext, but then the last line will generate a new query to the database, and i don't want that. What i would like is something like: Debug.WriteLine((member1.UserPhoto.IsPopulated()) ? member1.UserPhoto.ToString() : "none"); Debug.WriteLine((member2.UserPhoto.IsPopulated()) ? member2.UserPhoto.ToString() : "none"); Is it possible?

    Read the article

  • Silverlight: Binding to a LayoutRoot value from within a DataTemplate

    - by Rosarch
    I have a DataTemplate for a ListBox, where I have several controls that bind to an item. I would also like to bind to a value on LayoutRoot.DataContext. I'm unsure of how to do this. <!--LayoutRoot is the root grid where all page content is placed--> <StackPanel x:Name="LayoutRoot" Background="Transparent"> <ListBox ItemsSource="{Binding Items}"> <ListBox.ItemTemplate> <DataTemplate> <StackPanel> <TextBlock Text="{Binding}" /> <TextBlock Text="{Binding ElementName=LayoutRoot, Path=DataContext.Foo}" /> </StackPanel> </DataTemplate> </ListBox.ItemTemplate> </ListBox> </StackPanel> public partial class MainPage : PhoneApplicationPage { public string Foo { get { return "the moon"; } } private int startIndex = 1; private IList<string> _data = new List<string>() { "foo", "bar", "baz" }; public IList<string> Items { get { return _data; } } // Constructor public MainPage() { InitializeComponent(); LayoutRoot.DataContext = this; } } This doesn't work; only the _data items are displayed. The following binding errors appear in the Debug output: System.Windows.Data Error: BindingExpression path error: 'Foo' property not found on 'foo' 'System.String' (HashCode=1502598398). BindingExpression: Path='DataContext.Foo' DataItem='System.Windows.Controls.Border' (HashCode=78299055); target element is 'System.Windows.Controls.TextBlock' (Name=''); target property is 'Text' (type 'System.String').. System.Windows.Data Error: BindingExpression path error: 'Foo' property not found on 'bar' 'System.String' (HashCode=696029481). BindingExpression: Path='DataContext.Foo' DataItem='System.Windows.Controls.Border' (HashCode=78298703); target element is 'System.Windows.Controls.TextBlock' (Name=''); target property is 'Text' (type 'System.String').. System.Windows.Data Error: BindingExpression path error: 'Foo' property not found on 'baz' 'System.String' (HashCode=696029489). BindingExpression: Path='DataContext.Foo' DataItem='System.Windows.Controls.Border' (HashCode=78298694); target element is 'System.Windows.Controls.TextBlock' (Name=''); target property is 'Text' (type 'System.String').. Do I have a syntax error somewhere? Update I'm aiming for something that looks like this: foo the moon bar the moon baz the moon Instead, all I'm getting is: foo bar baz

    Read the article

< Previous Page | 3 4 5 6 7 8 9 10 11 12 13 14  | Next Page >