Search Results

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

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

  • Populate datagrid using Datacontext in C# WPF

    - by anon
    I'm trying to get data from file. The file first has three lines of text that describes the file, then there is a header for the data below. I've managed to extract that. What I'm having problems is getting the data below the header line. The data below the header line can look like "1 2 3 4 5 6 7 8 9 abc". DataGrid dataGrid1 = new DataGrid(); masterGrid.Children.Add(dataGrid1); using (TextReader tr = new StreamReader(@filename)) { int lineCount = 1; while (tr.Peek() >= 0) { string line = tr.ReadLine(); { string[] data = line.Trim().Split(' '); Dictionary<string, object> sensorData = new Dictionary<string, object>(); for (int i = 0, j = 0; i < data.Length; i++) { //I know that I'm delimiting the data by a space before. //but the data from the text file doesn't necessarily have //just one space between each piece of data //so if I don't do this, spaces will become part of the data. if (String.Compare(data[i]," ") > 0) { sensorData[head[j]] = data[i]; j++; } } sensorDatas.Add(sensorData); sensorData = null; } lineCount++; } } dataGrid1.DataContext = sensorDatas; I can't figure out why this doens't work. If I change "dataGrid1.DataContext = sensorDatas;" to "dataGrid1.ItemsSource = sensorDatas;" then I get the data in the proper columns, but I also get some Raw View data such as: Comparer, Count, Keys, Values as columns, which I don't want. Any insight?

    Read the article

  • Helping linqtosql datacontext use implicit conversion between varchar column in the database and tab

    - by user213256
    I am creating an mssql database table, "Orders", that will contain a varchar(50) field, "Value" containing a string that represents a slightly complex data type, "OrderValue". I am using a linqtosql datacontext class, which automatically types the "Value" column as a string. I gave the "OrderValue" class implicit conversion operators to and from a string, so I can easily use implicit conversion with the linqtosql classes like this: // get an order from the orders table MyDataContext db = new MyDataContext(); Order order = db.Orders(o => o.id == 1); // use implicit converstion to turn the string representation of the order // value into the complex data type. OrderValue value = order.Value; // adjust one of the fields in the complex data type value.Shipping += 10; // use implicit conversion to store the string representation of the complex // data type back in the linqtosql order object order.Value = value; // save changes db.SubmitChanges(); However, I would really like to be able to tell the linqtosql class to type this field as "OrderValue" rather than as "string". Then I would be able to avoid complex code and re-write the above as: // get an order from the orders table MyDataContext db = new MyDataContext(); Order order = db.Orders(o => o.id == 1); // The Value field is already typed as the "OrderValue" type rather than as string. // When a string value was read from the database table, it was implicity converted // to "OrderValue" type. order.Value.Shipping += 10; // save changes db.SubmitChanges(); In order to achieve this desired goal, I looked at the datacontext designer and selected the "Value" field of the "Order" table. Then, in properties, I changed "Type" to "global::MyApplication.OrderValue". The "Server Data Type" property was left as "VarChar(50) NOT NULL" The project built without errors. However, when reading from the database table, I was presented with the following error message: Could not convert from type 'System.String' to type 'MyApplication.OrderValue'. at System.Data.Linq.DBConvert.ChangeType(Object value, Type type) at Read_Order(ObjectMaterializer1 ) at System.Data.Linq.SqlClient.ObjectReaderCompiler.ObjectReader2.MoveNext() at System.Linq.Buffer1..ctor(IEnumerable1 source) at System.Linq.Enumerable.ToArray[TSource](IEnumerable`1 source) at Example.OrdersProvider.GetOrders() at ... etc From the stack trace, I believe this error is happening while reading the data from the table. When presented with converting a string to my custom data type, even though the implicit conversion operators are present, the DBConvert class gets confused and throws an error. Is there anything I can do to help it not get confused and do the implicit conversion? Thanks in advance, and apologies if I have posted in the wrong forum. cheers / Ben

    Read the article

  • WPF DataContext syntax - Convert from C# to VB

    - by hawbsl
    Currently working through a Teach Yourself WPF tutorial. Usually I can mentally convert from C# to VB without any problem but this C# syntax is unfamiliar. How is it written in VB? Private void Button_Click(object sender, RoutedEventArgs e) { ((Person)DataContext).FirstName = "blah blah" } My usual fave online converters are choking on this ... perhaps because they don't do WPF?

    Read the article

  • DataContext Refresh and PropertyChanging & PropertyChanged Events

    - by Scott
    I'm in a situation where I am being informed from an outside source that a particular entity has been altered outside my current datacontext. I'm able to find the entity and call refresh like so MyDataContext.Refresh(RefreshMode.OverwriteCurrentValues, myEntity); and the properties which have been altered on the entity are updated correctly. However neither of the INotifyPropertyChanging INotifyPropertyChanged appear to be raised when the refresh occurs and this leaves my UI displaying incorrect information. I'm aware that Refresh() fails to use the correct property getters and setters on the entity to raise the change notification events, but perhaps there is another way to accomplish the same thing? Am I doing something wrong? Is there a better method than Refresh? If Refresh is the only option, does anyone have a work around?

    Read the article

  • DataContext Doesn't Exist in Dynamic Data Project?

    - by davemackey
    This is really annoying...and I know it is something extremely simple... 1. I create a new Dynamic Data project. 2. I add a LINQ-to-SQL class and drag and drop some tables onto the class. 3. I open the global.asax.vb and uncomment the line: DefaultModel.RegisterContext(GetType(YourDataContext), New ContextConfiguration() With {.ScaffoldAllTables = True}) I remove YourDataContext and replace it with the DataContext from my LINQ-to-SQL class: DefaultModel.RegisterContext(GetType(NorthwindDataContext), New ContextConfiguration() With {.ScaffoldAllTables = True}) I then try to debug/build/etc. and receive the following error: Type 'NorthwindDataContext' is not defined Why is it not defined? It seems like its not recognizing I created the DBML file.

    Read the article

  • DataContext, DataBinding and Element Binding in Silverlight

    - by Matt
    I'm having one hell of a time trying to get my databinding to work correctly. I have reason to believe that what I'm trying to accomplish can't be done, but we'll see what answers I get. I've got a UserControl. This UserControl contains nothing more than a button. Now within the code behind, I've got a property name IsBookmarked. When IsBookmarked is set, code is run that animates the look of the button. The idea is that you click the button and it visually changes. We'll call this UserControl a Bookmark control. Now I have another control, which we'll call the FormControl. My FormControl contains a child Bookmark control. I've tried to do databinding on my Bookmark control, but it's not working. Here's some code to help you out. <UserControl ......> <q:Bookmark x:Name="BookMarkControl1" IsBookmarked="{Binding IsSiteBookmarked}" /> </UserControl> public void Control_Loaded(object sender, EventArgs e) { DataContext = new Employee { IsSiteBookmarked = True }; } public partial class Bookmark : UserControl { bool _IsSiteBookmarked= false; public bool IsSiteBookmarked { get {return _IsSiteBookmarked;} set { _IsSiteBookmarked= value; SwitchMode(value); } } }

    Read the article

  • WPF: How to bind and update display with DataContext

    - by Am
    I'm trying to do the following thing: I have a TabControl with several tabs. Each TabControlItem.Content points to PersonDetails which is a UserControl Each BookDetails has a dependency property called IsEditMode I want a control outside of the TabControl , named ToggleEditButton, to be updated whenever the selected tab changes. I thought I could do this by changing the ToggleEditButton data context, by it doesn't seem to work (but I'm new to WPF so I might way off) The code changing the data context: private void tabControl1_SelectionChanged(object sender, SelectionChangedEventArgs e) { if (e.Source is TabControl) { if (e.Source.Equals(tabControl1)) { if (tabControl1.SelectedItem is CloseableTabItem) { var tabItem = tabControl1.SelectedItem as CloseableTabItem; RibbonBook.DataContext = tabItem.Content as BookDetails; ribbonBar.SelectedTabItem = RibbonBook; } } } } The DependencyProperty under BookDetails: public static readonly DependencyProperty IsEditModeProperty = DependencyProperty.Register("IsEditMode", typeof (bool), typeof (BookDetails), new PropertyMetadata(true)); public bool IsEditMode { get { return (bool)GetValue(IsEditModeProperty); } set { SetValue(IsEditModeProperty, value); SetValue(IsViewModeProperty, !value); } } And the relevant XAML: <odc:RibbonTabItem Title="Book" Name="RibbonBook"> <odc:RibbonGroup Title="Details" Image="img/books2.png" IsDialogLauncherVisible="False"> <odc:RibbonToggleButton Content="Edit" Name="ToggleEditButton" odc:RibbonBar.MinSize="Medium" SmallImage="img/edit_16x16.png" LargeImage="img/edit_32x32.png" Click="Book_EditDetails" IsChecked="{Binding Path=IsEditMode, Mode=TwoWay}"/> ... There are two things I want to accomplish, Having the button reflect the IsEditMode for the visible tab, and have the button change the property value with no code behind (if posible) Any help would be greatly appriciated.

    Read the article

  • Is there anyway to stop automatic DataContext inheritance in Silverlight?

    - by Ant
    Is there anyway to stop automatic DataContext inheritance in Silverlight? I Set my DataContext on my parent UserControl in code. As a result all the xaml bindings inside the UserControl try to bind to the new DataConext they get (through the automatic DataContext Inheritance). The DataContext's for the children elements (actually they are children of children of children) of the UserControl is something I need to set in the UserControl's code... I don't want them being all smart because they end up binding to the wrong data object! :-)

    Read the article

  • Linq to SQL DataContext Windsor IoC memory leak problem

    - by Mr. Flibble
    I have an ASP.NET MVC app that creates a Linq2SQL datacontext on a per-web-request basis using Castler Windsor IoC. For some reason that I do not fully understand, every time a new datacontext is created (on every web request) about 8k of memory is taken up and not released - which inevitably causes an OutOfMemory exception. If I force garbage collection the memory is released OK. My datacontext class is very simple: public class DataContextAccessor : IDataContextAccessor { private readonly DataContext dataContext; public DataContextAccessor(string connectionString) { dataContext = new DataContext(connectionString); } public DataContext DataContext { get { return dataContext; } } } The Windsor IoC webconfig to instantiate this looks like so: <component id="DataContextAccessor" service="DomainModel.Repositories.IDataContextAccessor, DomainModel" type="DomainModel.Repositories.DataContextAccessor, DomainModel" lifestyle="PerWebRequest"> <parameters> <connectionString> ... </connectionString> </parameters> </component> Does anyone know what the problem is, and how to fix it?

    Read the article

  • Ninject caching an injected DataContext? Lifecycle Management?

    - by awrigley
    I had a series of very bizarre errors being thrown in my repositories. Row not found or changed, 1 of 2 updates failed... Nothing made sense. It was as if my DataContext instance was being cached... Nothing made sense and I was considering a career move. I then noticed that the DataContext instance was passed in using dependency injection, using Ninject (this is the first time I have used DI...). I ripped out the Dependency Injection, and all went back to normal. Instantly. So dependency injection was the issue, but I still don't know why. I am speculating that Ninject was caching the injected DataContext. Is this correct? Is there a way of configuring the lifecycle management of injected parameters? If so, what would be the best configuration to use to have the DataContext behave like a normal DataContext, ie, no caching across requests?

    Read the article

  • Using ASP.NET MVC, Linq To SQL, and StructureMap causing DataContext to cache data

    - by Dragn1821
    I'll start by telling my project setup: ASP.NET MVC 1.0 StructureMap 2.6.1 VB I've created a bootstrapper class shown here: Imports StructureMap Imports DCS.Data Imports DCS.Services Public Class BootStrapper Public Shared Sub ConfigureStructureMap() ObjectFactory.Initialize(AddressOf StructureMapRegistry) End Sub Private Shared Sub StructureMapRegistry(ByVal x As IInitializationExpression) x.AddRegistry(New MainRegistry()) x.AddRegistry(New DataRegistry()) x.AddRegistry(New ServiceRegistry()) x.Scan(AddressOf StructureMapScanner) End Sub Private Shared Sub StructureMapScanner(ByVal scanner As StructureMap.Graph.IAssemblyScanner) scanner.Assembly("DCS") scanner.Assembly("DCS.Data") scanner.Assembly("DCS.Services") scanner.WithDefaultConventions() End Sub End Class I've created a controller factory shown here: Imports System.Web.Mvc Imports StructureMap Public Class StructureMapControllerFactory Inherits DefaultControllerFactory Protected Overrides Function GetControllerInstance(ByVal controllerType As System.Type) As System.Web.Mvc.IController Return ObjectFactory.GetInstance(controllerType) End Function End Class I've modified the Global.asax.vb as shown here: ... Sub Application_Start() RegisterRoutes(RouteTable.Routes) 'StructureMap BootStrapper.ConfigureStructureMap() ControllerBuilder.Current.SetControllerFactory(New StructureMapControllerFactory()) End Sub ... I've added a Structure Map registry file to each of my three projects: DCS, DCS.Data, and DCS.Services. Here is the DCS.Data registry: Imports StructureMap.Configuration.DSL Public Class DataRegistry Inherits Registry Public Sub New() 'Data Connections. [For](Of DCSDataContext)() _ .HybridHttpOrThreadLocalScoped _ .Use(New DCSDataContext()) 'Repositories. [For](Of IShiftRepository)() _ .Use(Of ShiftRepository)() [For](Of IMachineRepository)() _ .Use(Of MachineRepository)() [For](Of IShiftSummaryRepository)() _ .Use(Of ShiftSummaryRepository)() [For](Of IOperatorRepository)() _ .Use(Of OperatorRepository)() [For](Of IShiftSummaryJobRepository)() _ .Use(Of ShiftSummaryJobRepository)() End Sub End Class Everything works great as far as loading the dependecies, but I'm having problems with the DCSDataContext class that was genereated by Linq2SQL Classes. I have a form that posts to a details page (/Summary/Details), which loads in some data from SQL. I then have a button that opens a dialog box in JQuery, which populates the dialog from a request to (/Operator/Modify). On the dialog box, the form has a combo box and an OK button that lets the user change the operator's name. Upon clicking OK, the form is posted to (/Operator/Modify) and sent through the service and repository layers of my program and updates the record in the database. Then, the RedirectToAction is called to send the user back to the details page (/Summary/Details) where there is a call to pull the data from SQL again, updating the details view. Everything works great, except the details view does not show the new operator that was selected. I can step through the code and see the DCSDataContext class being accessed to update the operator (which does actually change the database record), but when the DCSDataContext is accessed to reload the details objects, it pulls in the old value. I'm guessing that StructureMap is causing not only the DCSDataContext class but also the data to be cached? I have also tried adding the following to the Global.asax, but it just ends up crashing the program telling me the DCSDataContext has been disposed... Private Sub MvcApplication_EndRequest(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.EndRequest StructureMap.ObjectFactory.ReleaseAndDisposeAllHttpScopedObjects() End Sub Can someone please help?

    Read the article

  • Null Reference Exception In LINQ DataContext

    - by Frank
    I have a Null Reference Exception Caused by this code: var recentOrderers = (from p in db.CMS where p.ODR_DATE > DateTime.Today - new TimeSpan(60, 0, 0, 0) select p.SOLDNUM).Distinct(); result = (from p in db.CMS where p.ORDER_ST2 == "SH" && p.ODR_DATE > DateTime.Today - new TimeSpan(365, 0, 0, 0) && p.ODR_DATE < DateTime.Today - new TimeSpan(60, 0, 0, 0) && !(recentOrderers.Contains(p.SOLDNUM))/**/ select p.SOLDNUM).Distinct().Count(); result is of double type. When I comment out: !(recentOrderers.Contains(p.SOLDNUM)) The code runs fine. I have verified that recentOrderers is not null, and when I run: if(recentOrderes.Contains(0)) return; Execution follows this path and returns. Not sure what is going on, since I use similar code above it: var m = (from p in db.CMS where p.ORDER_ST2 == "SH" select p.SOLDNUM).Distinct(); double result = (from p in db.CUST join r in db.DEMGRAPH on p.CUSTNUM equals r.CUSTNUM where p.CTYPE3 == "cmh" && !(m.Contains(p.CUSTNUM)) && r.ColNEWMEMBERDAT.Value.Year > 1900 select p.CUSTNUM).Distinct().Count(); which also runs flawlessly. After noting the similarity, can anyone help? Thanks in advance. -Frank GTP, Inc.

    Read the article

  • linq to sql datacontext for a web application

    - by rap-uvic
    Hello, I'm trying to use linq to sql for my project (very short deadline), and I'm kind of in a bind. I don't know the best way to have a data context handy per request thread. I want something like a singleton class from which all my repository classes can access the current data context. However, singleton class is static and is not thread-safe and therefore not suitable for web apps. I want something that would create a data context at the beginning of the request and dispose of it along with the request. Can anyone please share their solution to this problem? I've been searching for a solution and I've found a good post from Rick Strahl : http://www.west-wind.com/weblog/posts/246222.aspx but I don't completely understand his thread-safe or business object approach. If somebody has a simplified version of his thread-safe approach, i'd love to take a look.

    Read the article

  • How to access a method on a generic datacontext which is only created at runtime

    - by Jeremy Holt
    I'm creating my generic DataContext using only the connectionString in the ctor. I have no issues in retrieving the table using DataContext.GetTable(). However, I need to also be able to retrieve entities of inline table functions. The dbml designer generates public IQueryable<testFunctionResult> testFunction() { return this.CreateMethodCallQuery<testFunctionResult>(this, ((MethodInfo)(MethodInfo.GetCurrentMethod()))); } The question is how do I get the MethodInfo.GetCurrentMethod() when the DataContext has no method called "testFunction", i.e.typeof(DataContext).GetMethod("testFunction") returns null? What I'm trying to achieve is something like: public class UnitofWork<T> { public UnitofWork(string connectionString) { this.DataContext = new DataContext(connectionString); } public UnitofWork(IQueryable<T> tableEntity) { _tableEntity = tableEntity; } public IQueryable<T> TableEntity { get { if (DataContext == null) return _tableEntity; var metaType = DataContext.Mapping.GetMetaType(typeof (T)); if (metaType.IsEntity) _tableEntity = DataContext.GetTable<T>(); else { var s = typeof(T).Name; string methodName = s.Substring(0, s.IndexOf("Result")) + "()"; // the designer automatically affixes "Result" to the type name // Make a method from methodName // _tableEntity = DataContext.CreateMethodCallQuery(DataContext, method, new object[]{}); } return _tableEntity; } set { _tableEntity = value; } } ) Thanks in advance for any insight Jeremy

    Read the article

  • WPF: Setting DataContext of a UserControl with Binding not working in XAML

    - by Grant Crofton
    Hi, I'm trying to get my first WPF app working using MVVM, and I've hit a little binding problem. The setup is that I have a view & viewModel which holds User details (the parent), and to try and keep things simple I've put a section of that view into a separate view & viewModel (the child). The child view is defined as a UserControl. The issue I'm having is how to set the DataContext of the child view (the UserControl). My parent ViewModel has a property which exposes the child ViewModel, like so: class ParentViewModel: INotifyPropertyChanged { public ChildViewModel childViewModel { get; set; } //... } In the XAML for my parent view (which has it's DataContext set to the ParentViewModel), I try to set the DataContext of the child view as follows: <views:ChildView x:Name="ChildView" DataContext="{Binding childViewModel}"/> However, this doesn't work. The DataContext of the child view is set to the same DataContext as the parent view (i.e. the ParentViewModel), as if I wasn't setting it at all. I also tried setting the DataContext in the child view itself, which also doesn't work: <UserControl x:Class="DietRecorder.Client.View.ChildView" DataContext="childViewModel" I have found a couple of ways around this. In the child view, I can bind everything by including the ChildViewModel in the path: <SomeControl Visibility="{Binding Path=childViewModel.IsVisible}"> but I don't want the child view to have this level of awareness of the hierarchy. Setting the DataContext in code also works - however, I have to do this after showing the parent view, otherwise the DataContext just gets overwritten when I call Show(): parentView.Show(); parentView.ChildView.DataContext = parentViewModel.childViewModel; This code also makes me feel uneasy, what with the LOD violation and all. It's just the DataContext that seems to be the problem - I can bind other things in the child, for example I tried binding the FontSize to an int property just to test it: <views:ChildView x:Name="ChildView" FontSize="{Binding Path=someVal}"/> And that works fine. But I'm sure binding the DataContext should work - I've seen similar examples of this kind of thing. Have I missed something obvious here? Is there a reason this won't work? Is there a spelling mistake somewhere? (I renamed things for your benefit so you won't be able to help me there anyway). Any thoughts welcome. Thanks, Grant

    Read the article

  • Linq-to-sql Compiled Query is returning result from different DataContext

    - by Vladimir Kojic
    Compiled query: public static Func<OperationalDataContext, short, Machine> QueryMachineById = CompiledQuery.Compile((OperationalDataContext db, short machineID) => db.Machines.Where(m => m.MachineID == machineID).SingleOrDefault()); It looks like compiled query is caching Machine object and returning the same object even if query is called from new DataContext (I’m disposing DataContext in the service but I’m getting Machine from previous DataContext). I use POCOs and XML mapping. Revised: It looks like compiled query is returning result from new data context and it is not using the one that I passed in compiled-query. Therefore I can not reuse returned object and link it to another object obtained from datacontext thru non compiled queries. I’m using unit of work pattern : // First Call Using(new DataContext) { Machine from DataContext.Table == machine from cached query } // Do some work // Second Call is failing Using(new DataContext) { Machine from DataContext.Table <> machine from cached query }

    Read the article

  • Is there a cleaner way to Bind property to owner's DataContext?

    - by Dan Bryant
    I have some code that looks like this: <Expander Header="{Binding SelectedSlot.Name}" Visibility="{Binding ShowGroupSlot, Converter={StaticResource BooleanToVisibility}}"> <Controls:GroupPrototypeSlotControl Slot="{Binding DataContext.SelectedSlot, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type Expander}}}" /> </Expander> This works, but the ugliness of the Slot Binding bothers me. This is required because the GroupPrototypeSlotControl has a GroupPrototypeViewModel as its DataContext. If I simply use {Binding SelectedSlot}, it attempts to resolve it on the 'child' ViewModel, which fails. I get around this by explicitly looking at the DataContext of my parent control. Is there a cleaner way to do this type of binding?

    Read the article

  • C# Linq: Can you merge DataContexts?

    - by Andreas Grech
    Say I have one database, and this database has a set of tables that are general to all Clients and some tables that are specific to certain clients. Now what I have in mind is creating a primary DataContext that includes only the tables that are general to all the clients, and then create separate DataContexts that contain only the tables that are specific to the client. Is there a way to kind of "merge" DataContexts so that it becomes one context? So for Client A, I need one DataContext that includes both the general tables and also the tables for that specific client (retrieved from two different DataContexts) ? [Update] What I think I can do is, from the Partial Class of the DataContext instead of letting my DataContext inherit from DataContext I make it inherit from MyDataContext; that way, the tables from MyDataContext and the other DataContext will be available in one DataContext class. What do you think about this approach? Of course with something like this you can only merge two datacontexts at once though...

    Read the article

  • Using MS Moles with datacontext and stored procedures without using a Connection string.

    - by Brian
    I have just begun to work with MS Moles for testing and I have followed the idea/pattern in which jcollum(thanks) uses a Mole for a table in this stackoverflow question here. But I am having a problem as I do not want to have to pass a connection string when I use the datasource as such: using (TheDataContext dataContext = new TheDataContext(myConnectionString)) { dataContext.ExecuteStoredprocedure(value, ref ValueExists); } I really like the fact that I just need to mole the table and everything else is done for me. I realize I could just mole the ExecuteStoredProcedure method, but I am wondering if I could just somehow avoid the sql exception I am getting here when I do not pass in the connection string. Or, if I there is a better way to do this? Therefore, does anyone have a solution so that I can avoid placing in the connection string? Thanks in advance.

    Read the article

  • Linq-to-sql Compiled Query returns object NOT belonging to submitted DataContext ?

    - by Vladimir Kojic
    Compiled query: public static class Machines { public static readonly Func<OperationalDataContext, short, Machine> QueryMachineById = CompiledQuery.Compile((OperationalDataContext db, short machineID) => db.Machines.Where(m => m.MachineID == machineID).SingleOrDefault() ); public static Machine GetMachineById(IUnitOfWork unitOfWork, short id) { Machine machine; // Old code (working) //var machineRepository = unitOfWork.GetRepository<Machine>(); //machine = machineRepository.Find(m => m.MachineID == id).SingleOrDefault(); // New code (making problems) machine = QueryMachineById(unitOfWork.DataContext, id); return machine; } It looks like compiled query is returning result from another data context [TestMethod] public void GetMachinesTest() { using (var unitOfWork = IoC.Get<IUnitOfWork>()) { // Compile Query var machine = Machines.GetMachineById(unitOfWork, 3); } using (var unitOfWork = IoC.Get<IUnitOfWork>()) { var machineRepository = unitOfWork.GetRepository<Machine>(); // Get From Repository var machineFromRepository = machineRepository.Find(m => m.MachineID == 2).SingleOrDefault(); var machine = Machines.GetMachineById(unitOfWork, 2); VerifyHuskyHostMachine(machineFromRepository, 2, "Machine 2", "222222", "H400RS", "MachineIconB.xaml", false, true, LicenseType.Licensed, InterfaceType.HuskyHostV2, "10.0.97.2:8080", "10.0.97.2", 8080, "4.0"); VerifyHuskyHostMachine(machine, 2, "Machine 2", "222222", "H400RS", "MachineIconB.xaml", false, true, LicenseType.Licensed, InterfaceType.HuskyHostV2, "10.0.97.2:8080", "10.0.97.2", 8080, "4.0"); Assert.AreSame(machineFromRepository, machine); // FAIL } } If I run other (complex) unit tests I'm getting as expected: An attempt has been made to Attach or Add an entity that is not new, perhaps having been loaded from another DataContext. Another Important information is that this test is under TransactionScope! UPDATE: It looks like next link is describing similar problem (is this bug solved ?): http://social.msdn.microsoft.com/Forums/en-US/linqprojectgeneral/thread/9bcffc2d-794e-4c4a-9e3e-cdc89dad0e38

    Read the article

  • Linq-to-sql Compiled Query is caching result from disposed DataContext

    - by Vladimir Kojic
    Compiled query: public static Func<OperationalDataContext, short, Machine> QueryMachineById = CompiledQuery.Compile((OperationalDataContext db, short machineID) => db.Machines.Where(m => m.MachineID == machineID).SingleOrDefault()); It looks like compiled query is caching Machine object and returning the same object even if query is called from new DataContext (I’m disposing DataContext in the service but I’m getting Machine from previous DataContext). I use POCOs and XML mapping. Getting cached object from the same datacontext is ok, but when I call query with new DataContext I don’t want to get object from old datacontext. Is there something that I don’t do right ? Thanks, Vladimir

    Read the article

  • Use DataContext to create schema in an existing blank database file?

    - by jdk
    With a DataContext and a blank file-based database that already exists, is it possible to write the Data Context classes (i.e. the ones I added to the designer) to create the db schema? With a data context I only see the abilities to either: create a new database file and have its structure created at the same time, or to populate data into an existing database having preexisting schema. I'm looking for a hybrid solution between those two worlds. Update 1: My proof that a preexisting db is not compatible with the Data Context CreateDatabase() operation is this error Database 'C:...\App_Data\IntermediateData.mdf' already exists. Choose a different database name. based on this code using (IntermediateClassesDataContext intermediateContext = new IntermediateClassesDataContext(_getIntermediateConn())) { intermediateContext.CreateDatabase(); }

    Read the article

  • Where should I set the DataContext - code behind or xaml?

    - by dovholuk
    (honestly I searched and read all the 'related questions' that seemed relevant - i do hope i didn't "miss" this question from elsewhere but here goes...) There are two different ways (at least) to set the DataContext. One can use XAML or one can use the code behind. What is the 'best practice' and why? I tend to favor setting it in XAML because it allows a designer to define collections on their own but I need 'ammunition' on why it's a best practice or why I'm crazy and the code behind is the bomb...

    Read the article

  • L2S DataContext out of synch: row not found or changed

    - by awrigley
    The Problem I am getting a number of errors that imply that the DataContext, or rather, the way I am using the DataContext is getting out of synch. The error occurs on db.SubmitChanges() where db is my DataContext instance. The error is: Row not found or changed. The problem only occurs intermitently, for example, adding a row then deleting it. If I stop the dev server and restart, the added row is there and I can delete it no problem. Ie, it seems that the problem is related to the DataContext losing track of the rows that have been added. IMPORTANT: Before anyone votes to close this thread, on the basis of it being a duplicate, I have checked the sql server profiler and there is no "Where 0 = 1" in the SQL. I have also recreated the dbml file, so am satisfied that the database schema is in synch with the schema represented by the dbml file. Ie, no cases of mismatched nullable/not nullable columns, etc. My Diagnosis (for what it is worth): It seems to be a problem related to how I am using the DataContext. I am new to MVC, Repositories and Services patterns, so suspect that I have wired things up wrong. The Setup Simple eLearning app in its early stages. Pupils need to be able to add and delete courses (Courses table) to their UserCourses. To do this, I have a service that gets a specific DataContext instance Dependency Injected into its constructor. Service Class Constructor: public class SqlPupilBlockService : IPupilBlockService { DataContext db; public SqlPupilBlockService(DataContext db) { this.db = db; CoursesRepository = new SqlRepository<Course>(db); UserCoursesRepository = new SqlRepository<UserCourse>(db); } // Etc, etc } The CoursesRepository and UserCoursesRepository are both private properties of the service class that are of Type IRepository (just a simple generic repository interface). Sql Respoitory Code: public class SqlRepository<T> : IRepository<T> where T : class { DataContext db; public SqlRepository(DataContext db) { this.db = db; } #region IRepository<T> Members public IQueryable<T> Query { get { return db.GetTable<T>(); } } public List<T> FetchAll() { return Query.ToList(); } public void Add(T entity) { db.GetTable<T>().InsertOnSubmit(entity); } public void Delete(T entity) { db.GetTable<T>().DeleteOnSubmit(entity); } public void Save() { db.SubmitChanges(); } #endregion } The two methods for adding and deleting UserCourses are: Service Methods for Adding and Deleting UserCourses: public void AddUserCourse(int courseId) { UserCourse uc = new UserCourse(); uc.IdCourse = courseId; uc.IdUser = UserId; uc.DateCreated = DateTime.Now; uc.DateAmended = DateTime.Now; uc.Role = "Pupil"; uc.CourseNotes = string.Empty; uc.ActiveStepIndex = 0; UserCoursesRepository.Add(uc); UserCoursesRepository.Save(); } public void DeleteUserCourse(int courseId) { var uc = (UserCoursesRepository.Query.Where(x => x.IdUser == UserId && x.IdCourse == courseId)).Single(); UserCoursesRepository.Delete(uc); UserCoursesRepository.Save(); } Ajax I am using Ajax via Ajax.BeginForm I don't think that is relevant. ASP.NET MVC 3 I am using mvc3, but don't think that is relevant: the errors are related to model code.

    Read the article

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