Search Results

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

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

  • DataContext to DB

    - by JD
    Hi all, I have designed my DB using the ORM in VS 2008. What is the best way to export this to an SQL server so it will create the tables and relations on SQL Server? Thanks, JD

    Read the article

  • C# Linq to SQL connection string (newbie)

    - by Chris'o
    i am a new linq to sql learner and this is my very first attempt to create a data viewer program. The idea is simple, i'd like to create a software that is able to view content of a table in a database. That's it. I got an early problem here already and i have seen many tutes and articles online but I still cant fix the bug. Here is my code: static void Main(string[] args) { string cs = "Data Source=localhost;Initial Catalog=somedb;Integrated Security=SSPI;"; var db = new DataClasses1DataContext(cs); db.Connection.Open(); foreach (var b in db.Mapping.GetTables()) Console.WriteLine(b.TableName); Console.ReadKey(true); } When I tried to check db.connection.equals(null); it returns false, so i thought i have connected successfully to the database since there is no error at all. But the code above doesn't print anything out to the screen. I kind of lost and don't know what's going on here. Does anyone know what is going wrong here?

    Read the article

  • Two DomainContext or data sources with WCF RIA - Silverlight page

    - by Mayur Kotlikar
    I am writting a Silverlight Business Application with WCF RIA link. I have 2 databases on same SQL server, Public and Private. The Public database contains a table which is mostly for public access level, like "user" table which has basic user information The Private database contains a table which has "private" information, user bank transactions etc I created 2 ADO.Net entity models, one each for Private and Public database and selected the tables. I also created 2 different domain context services On on Silverlight page, I need to get information from the tables that are across 2 databases, Private and Public as described above. How do I achieve this? I am thinking of some kind of a wrapper that internally gets data from domain services. Whats the best approach?

    Read the article

  • Silverlight - Access the Layout Grid's DataContext in a DataGrid CellTemplate's DataTemplate?

    - by Sudeep
    Hi, I am using Silverlight 3 to develop an application. In my app, I have a layout Grid (named "LayoutGrid") in which I have a DataGrid (named "PART_datagrid") with DataGridTemplateColumns. The LayoutGrid is set a DataContext in which there is a Ladders list as a property. This Ladders list is set as the ItemsSource for the PART_datagrid. <Grid x:Name="LayoutRoot"> <DataGrid x:Name="PART_datagrid" ItemsSource="{Binding Ladders}"> ... <DataGridTemplateColumn> <DataGridTemplateColumn.CellTemplate> <DataTemplate> <Button Name="DeleteLadder" Click.Command="{Binding ElementName=LayoutRoot, Path=DataContext.DeleteLadderCommand}" /> Now in one of the DataGridTemplateColumns I have a button which should invoke a Command thats present in the LayoutGrid's DataContext. So I tried Element-To-Element binding on my DataTemplate button as follows <Button Name="DeleteLadder" Click.Command="{Binding ElementName=LayoutRoot, Path=DataContext.DeleteLadderCommand}" /> But this does not seem to work. What I want to achieve is to handle the event of deletion of a DataGrid row at the parent DataContext level using the command. Can someone pls suggest how do I proceed on this? Thanks in advance...

    Read the article

  • Can I check wheter Linq 2 SQL's DataContext is tracking entities?

    - by Thomas Jespersen
    We want to throw an exception, if a user calls DataContext.SubmitChanges() and the DataContext is not tracking anything. That is... it is OK to call SubmitChanges if there are no inserts, updates or deletes. But we want to ensure that the developer didn't forget to attach the entity to the DataContext. Even better... is it possible to get a collection of all entities that the DataContext is tracking (including those that are not changed)? PS: The last question I asked were answered with: "do it this way instead"... please don't :-)

    Read the article

  • WPF Binding with RelativeSource of Window Requires "DataContext" in Path?

    - by Phil Sandler
    The following code works, but I'm curious as to why I need the Path to be prefixed with "DataContext"? In most other cases, the path used is relative to DataContext. Is it because I am using a RelativeSource? Because the source is at the root level (Window)? <Style TargetType="TextBox"> <Setter Property="IsReadOnly" Value="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}, Path=DataContext.IsReadOnly}"/> </Style>

    Read the article

  • Attach an entity that is not new, perhaps having been loaded from another DataContext. LINQ to SQL -

    - by soldieraman
    Alright How I got this error I got one application sitting on a server 2 users accessing this application - doing some bulk data processing . eg. entering values and then the application is working with another system to extract values for them and then saving. I can't recreate the error The error logs show: The error happend at the same time in both the application Both happend on a Attach/Submit (but two different functions) There is no way they are using the same DataContext object as I save the DataContext in the HttpContext.Items My hunch / guess is: One datacontext was not refreshed i.e. the an object was created for the same item twice as it was new in both the forms. eg. Customer Number - a customer was created (as one couldn't be found) by one datacontext - the other one couldn't find it either (i am using compiled queries to find it in the datacontext) so it created another object and on attaching failed. The HttpContext.Items lost its value somehow (i am using a virtual pc as server - maybe something went wrong there) I am going more of the second as I can't recreate the error - but it just might be a timing (for attach/save) thing - also the error makes me think of the 2nd too.

    Read the article

  • Using RIA DomainServices with ASP.NET and MVC 2

    - by Bobby Diaz
    Recently, I started working on a new ASP.NET MVC 2 project and I wanted to reuse the data access (LINQ to SQL) and business logic methods (WCF RIA Services) that had been developed for a previous project that used Silverlight for the front-end.  I figured that I would be able to instantiate the various DomainService classes from within my controller’s action methods, because after all, the code for those services didn’t look very complicated.  WRONG!  I didn’t realize at first that some of the functionality is handled automatically by the framework when the domain services are hosted as WCF services.  After some initial searching, I came across an invaluable post by Joe McBride, which described how to get RIA Service .svc files to work in an MVC 2 Web Application, and another by Brad Abrams.  Unfortunately, Brad’s solution was for an earlier preview release of RIA Services and no longer works with the version that I am running (PDC Preview). I have not tried the RC version of WCF RIA Services, so I am not sure if any of the issues I am having have been resolved, but I wanted to come up with a way to reuse the shared libraries so I wouldn’t have to write a non-RIA version that basically did the same thing.  The classes I came up with work with the scenarios I have encountered so far, but I wanted to go ahead and post the code in case someone else is having the same trouble I had.  Hopefully this will save you a few headaches! 1. Querying When I first tried to use a DomainService class to perform a query inside one of my controller’s action methods, I got an error stating that “This DomainService has not been initialized.”  To solve this issue, I created an extension method for all DomainServices that creates the required DomainServiceContext and passes it to the service’s Initialize() method.  Here is the code for the extension method; notice that I am creating a sort of mock HttpContext for those cases when the service is running outside of IIS, such as during unit testing!     public static class ServiceExtensions     {         /// <summary>         /// Initializes the domain service by creating a new <see cref="DomainServiceContext"/>         /// and calling the base DomainService.Initialize(DomainServiceContext) method.         /// </summary>         /// <typeparam name="TService">The type of the service.</typeparam>         /// <param name="service">The service.</param>         /// <returns></returns>         public static TService Initialize<TService>(this TService service)             where TService : DomainService         {             var context = CreateDomainServiceContext();             service.Initialize(context);             return service;         }           private static DomainServiceContext CreateDomainServiceContext()         {             var provider = new ServiceProvider(new HttpContextWrapper(GetHttpContext()));             return new DomainServiceContext(provider, DomainOperationType.Query);         }           private static HttpContext GetHttpContext()         {             var context = HttpContext.Current;   #if DEBUG             // create a mock HttpContext to use during unit testing...             if ( context == null )             {                 var writer = new StringWriter();                 var request = new SimpleWorkerRequest("/", "/",                     String.Empty, String.Empty, writer);                   context = new HttpContext(request)                 {                     User = new GenericPrincipal(new GenericIdentity("debug"), null)                 };             } #endif               return context;         }     }   With that in place, I can use it almost as normally as my first attempt, except with a call to Initialize():     public ActionResult Index()     {         var service = new NorthwindService().Initialize();         var customers = service.GetCustomers();           return View(customers);     } 2. Insert / Update / Delete Once I got the records showing up, I was trying to insert new records or update existing data when I ran into the next issue.  I say issue because I wasn’t getting any kind of error, which made it a little difficult to track down.  But once I realized that that the DataContext.SubmitChanges() method gets called automatically at the end of each domain service submit operation, I could start working on a way to mimic the behavior of a hosted domain service.  What I came up with, was a base class called LinqToSqlRepository<T> that basically sits between your implementation and the default LinqToSqlDomainService<T> class.     [EnableClientAccess()]     public class NorthwindService : LinqToSqlRepository<NorthwindDataContext>     {         public IQueryable<Customer> GetCustomers()         {             return this.DataContext.Customers;         }           public void InsertCustomer(Customer customer)         {             this.DataContext.Customers.InsertOnSubmit(customer);         }           public void UpdateCustomer(Customer currentCustomer)         {             this.DataContext.Customers.TryAttach(currentCustomer,                 this.ChangeSet.GetOriginal(currentCustomer));         }           public void DeleteCustomer(Customer customer)         {             this.DataContext.Customers.TryAttach(customer);             this.DataContext.Customers.DeleteOnSubmit(customer);         }     } Notice the new base class name (just change LinqToSqlDomainService to LinqToSqlRepository).  I also added a couple of DataContext (for Table<T>) extension methods called TryAttach that will check to see if the supplied entity is already attached before attempting to attach it, which would cause an error! 3. LinqToSqlRepository<T> Below is the code for the LinqToSqlRepository class.  The comments are pretty self explanatory, but be aware of the [IgnoreOperation] attributes on the generic repository methods, which ensures that they will be ignored by the code generator and not available in the Silverlight client application.     /// <summary>     /// Provides generic repository methods on top of the standard     /// <see cref="LinqToSqlDomainService&lt;TContext&gt;"/> functionality.     /// </summary>     /// <typeparam name="TContext">The type of the context.</typeparam>     public abstract class LinqToSqlRepository<TContext> : LinqToSqlDomainService<TContext>         where TContext : System.Data.Linq.DataContext, new()     {         /// <summary>         /// Retrieves an instance of an entity using it's unique identifier.         /// </summary>         /// <typeparam name="TEntity">The type of the entity.</typeparam>         /// <param name="keyValues">The key values.</param>         /// <returns></returns>         [IgnoreOperation]         public virtual TEntity GetById<TEntity>(params object[] keyValues) where TEntity : class         {             var table = this.DataContext.GetTable<TEntity>();             var mapping = this.DataContext.Mapping.GetTable(typeof(TEntity));               var keys = mapping.RowType.IdentityMembers                 .Select((m, i) => m.Name + " = @" + i)                 .ToArray();               return table.Where(String.Join(" && ", keys), keyValues).FirstOrDefault();         }           /// <summary>         /// Creates a new query that can be executed to retrieve a collection         /// of entities from the <see cref="DataContext"/>.         /// </summary>         /// <typeparam name="TEntity">The type of the entity.</typeparam>         /// <returns></returns>         [IgnoreOperation]         public virtual IQueryable<TEntity> GetEntityQuery<TEntity>() where TEntity : class         {             return this.DataContext.GetTable<TEntity>();         }           /// <summary>         /// Inserts the specified entity.         /// </summary>         /// <typeparam name="TEntity">The type of the entity.</typeparam>         /// <param name="entity">The entity.</param>         /// <returns></returns>         [IgnoreOperation]         public virtual bool Insert<TEntity>(TEntity entity) where TEntity : class         {             //var table = this.DataContext.GetTable<TEntity>();             //table.InsertOnSubmit(entity);               return this.Submit(entity, null, DomainOperation.Insert);         }           /// <summary>         /// Updates the specified entity.         /// </summary>         /// <typeparam name="TEntity">The type of the entity.</typeparam>         /// <param name="entity">The entity.</param>         /// <returns></returns>         [IgnoreOperation]         public virtual bool Update<TEntity>(TEntity entity) where TEntity : class         {             return this.Update(entity, null);         }           /// <summary>         /// Updates the specified entity.         /// </summary>         /// <typeparam name="TEntity">The type of the entity.</typeparam>         /// <param name="entity">The entity.</param>         /// <param name="original">The original.</param>         /// <returns></returns>         [IgnoreOperation]         public virtual bool Update<TEntity>(TEntity entity, TEntity original)             where TEntity : class         {             if ( original == null )             {                 original = GetOriginal(entity);             }               var table = this.DataContext.GetTable<TEntity>();             table.TryAttach(entity, original);               return this.Submit(entity, original, DomainOperation.Update);         }           /// <summary>         /// Deletes the specified entity.         /// </summary>         /// <typeparam name="TEntity">The type of the entity.</typeparam>         /// <param name="entity">The entity.</param>         /// <returns></returns>         [IgnoreOperation]         public virtual bool Delete<TEntity>(TEntity entity) where TEntity : class         {             //var table = this.DataContext.GetTable<TEntity>();             //table.TryAttach(entity);             //table.DeleteOnSubmit(entity);               return this.Submit(entity, null, DomainOperation.Delete);         }           protected virtual bool Submit(Object entity, Object original, DomainOperation operation)         {             var entry = new ChangeSetEntry(0, entity, original, operation);             var changes = new ChangeSet(new ChangeSetEntry[] { entry });             return base.Submit(changes);         }           private TEntity GetOriginal<TEntity>(TEntity entity) where TEntity : class         {             var context = CreateDataContext();             var table = context.GetTable<TEntity>();             return table.FirstOrDefault(e => e == entity);         }     } 4. Conclusion So there you have it, a fully functional Repository implementation for your RIA Domain Services that can be consumed by your ASP.NET and MVC applications.  I have uploaded the source code along with unit tests and a sample web application that queries the Customers table from inside a Controller, as well as a Silverlight usage example. As always, I welcome any comments or suggestions on the approach I have taken.  If there is enough interest, I plan on contacting Colin Blair or maybe even the man himself, Brad Abrams, to see if this is something worthy of inclusion in the WCF RIA Services Contrib project.  What do you think? Enjoy!

    Read the article

  • Tracking changes in Entity Framework 4.0 using POCO Dynamic Proxies across multiple data contexts.

    - by Rob Packwood
    I started messing with EF 4.0 because I am curious about the POCO possibilities... I wanted to simulate disconnected web environment and wrote the following code to simulate this: Save a test object in the database. Retrieve the test object Dispose of the DataContext associated with the test object I used to retrieve it Update the test object Create a new data context and persist the changes on the test object that are automatically tracked within the DynamicProxy generated against my POCO object. The problem is that when I call dataContext.SaveChanges in the Test method above, the updates are not applied. The testStore entity shows a status of "Modified" when I check its EntityStateTracker, but it is no longer modified when I view it within the new dataContext's Stores property. I would have thought that calling the Attach method on the new dataContext would also bring the object's "Modified" state over, but that appears to not be the case. Is there something I am missing? I am definitely working with self-tracking POCOs using DynamicProxies. private static void SaveTestStore(string storeName = "TestStore") { using (var context = new DataContext()) { Store newStore = context.Stores.CreateObject(); newStore.Name = storeName; context.Stores.AddObject(newStore); context.SaveChanges(); } } private static Store GetStore(string storeName = "TestStore") { using (var context = new DataContext()) { return (from store in context.Stores where store.Name == storeName select store).SingleOrDefault(); } } [Test] public void Test_Store_Update_Using_Different_DataContext() { SaveTestStore(); Store testStore = GetStore(); testStore.Name = "Updated"; using (var dataContext = new DataContext()) { dataContext.Stores.Attach(testStore); dataContext.SaveChanges(SaveOptions.DetectChangesBeforeSave); } Store updatedStore = GetStore("Updated"); Assert.IsNotNull(updatedStore); }

    Read the article

  • Automatic .NET code, nhibernate session, and LINQ datacontext clean-up?

    - by AverageJoe719
    Hi all, in my goal to adopt better coding practices I have a few questions in general about automatic handling of code. I have heard different answers both from online and talking with other developers/programmers at my work. I am not sure if I should have split them into 3 questions, but they all seem sort of related: 1) How does .NET handle instances of classes and other code things that take up memory? I recently found out about using the factory pattern for certain things like service classes so that they are only instantiated once in the entire application, but then I was told that '.NET handles a lot of that stuff automatically when mentioning it.' 2) How does Nhibernate's session handle automatic clean-up of un-used things? I've seen some say that it is great at handling things automatically and you should just use a session factory and that's it, no need to close it. But I have also read and seem many examples where people close the hibernate session. 3) How does LINQ's datacontext handle this? Most of the time I never .disposed my datacontext's and the app didn't see to take a performance hit (though I am not running anything super intensively), but it seems like most people recommend disposing of your datacontext after you are done with it. However, I have seen many many code examples where the dispose method is never called. Also in general I found it kind of annoying that you couldn't access even one-deep child related objects after disposing of the datacontext unless you explicity also grabbed them in the query. Thanks all. I am loving this site so far, I kind of get lost and spend hours just reading things on here. =)

    Read the article

  • What is the differnce between DataTemplate and DataContext in WPF?

    - by Ashish Ashu
    I can set the relationship b/w View Model and view through following DataContext syntax: <UserControl.DataContext> <view_model:MainMenuModel /> </UserControl.DataContext> And I can also set the relationship b/w View Model and view through following DataTemplate syntax: <DataTemplate DataType="{x:Type viewModel:UserViewModel}"> <view:UserView /> </DataTemplate> Please let me know what is the difference between the two ? Is the second XAML does not set the data context of a view ?

    Read the article

  • How do I set a ViewModel on a window in XAML using DataContext property?

    - by Nicholas
    The question pretty much says it all. I have a window, and have tried to set the DataContext using the full namespace to the ViewModel, but I seem to be doing something wrong. <Window x:Class="BuildAssistantUI.BuildAssistantWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" DataContext="BuildAssistantUI.ViewModels.MainViewModel">

    Read the article

  • Why is it possible to enumerate a LinqToSql query after calling Dispose() on the DataContext?

    - by DanM
    I'm using the Repository Pattern with some LinqToSql objects. My repository objects all implement IDisposable, and the Dispose() method does only thing--calls Dispose() on the DataContext. Whenever I use a repository, I wrap it in a using person, like this: public IEnumerable<Person> SelectPersons() { using (var repository = _repositorySource.GetNew<Person>(dc => dc.Person)) { return repository.GetAll(); } } This method returns an IEnumerable<Person>, so if my understanding is correct, no querying of the database actually takes place until Enumerable<Person> is traversed (e.g., by converting it to a list or array or by using it in a foreach loop), as in this example: var persons = gateway.SelectPersons(); // Dispose() is fired here var personViewModels = ( from b in persons select new PersonViewModel { Id = b.Id, Name = b.Name, Age = b.Age, OrdersCount = b.Order.Count() }).ToList(); // executes queries In this example, Dispose() gets called immediately after setting persons, which is an IEnumerable<Person>, and that's the only time it gets called. So, a couple questions: How does this work? How can a disposed DataContext still query the database for results when I walk the IEnumerable<Person>? What does Dispose() actually do? I've heard that it is not necessary (e.g., see this question) to dispose of a DataContext, but my impression was that it's not a bad idea. Is there any reason not to dispose of it?

    Read the article

  • Filtering in a HierarchicalDataTemplate via MarkupExtension?

    - by Dan Bryant
    I'm trying to create a MarkupExtension to allow filtering of items in an ItemsSource of a HierarchicalDataTemplate. In particular, I'd like to be able to supply a method name that will be executed on the DataContext in order to perform the filtering. The usage syntax I'm after looks like this: <HierarchicalDataTemplate DataType="{x:Type src:DeviceBindingViewModel}" ItemsSource="{Utilities:FilterCollection {Binding Definition.Entries}, MethodName=FilterEntries}"> <StackPanel Orientation="Horizontal"> <Image Source="{StaticResource BindingImage}" Width="24" Height="24" Margin="3"/> <TextBlock Text="{Binding DisplayName}" FontSize="12" VerticalAlignment="Center"/> </StackPanel> </HierarchicalDataTemplate> My code for the custom MarkupExtension looks like this: public sealed class FilterCollectionExtension : MarkupExtension { private readonly MultiBinding _binding; private Predicate<Object> _filterMethod; public string MethodName { get; set; } public FilterCollectionExtension(Binding binding) { _binding = new MultiBinding(); _binding.Bindings.Add(binding); //We package a reference to the DataContext with the binding so that the Converter has access to it var selfBinding = new Binding {RelativeSource = RelativeSource.Self}; _binding.Bindings.Add(selfBinding); _binding.Converter = new InternalConverter(this); } public FilterCollectionExtension(Binding binding, string methodName) : this(binding) { MethodName = methodName; } public override object ProvideValue(IServiceProvider serviceProvider) { return _binding; } private bool FilterInternal(Object dataContext, Object value) { //Filtering is only applicable if a DataContext is defined if (dataContext != null) { if (_filterMethod == null) { var type = dataContext.GetType(); var method = type.GetMethod(MethodName, new[] { typeof(Object) }); if (method == null || method.ReturnType != typeof(bool)) throw new InvalidOperationException("Could not locate a filter predicate named " + MethodName + " on the DataContext"); _filterMethod = (Predicate<Object>)Delegate.CreateDelegate(typeof(Predicate<Object>), dataContext, method); } else { if (_filterMethod.Target != dataContext) { _filterMethod = (Predicate<Object>) Delegate.CreateDelegate(typeof (Predicate<Object>), dataContext, _filterMethod.Method); } } if (_filterMethod != null) return _filterMethod(value); } //If no filtering resolved, just allow all elements return true; } private class InternalConverter : IMultiValueConverter { private readonly FilterCollectionExtension _owner; public InternalConverter(FilterCollectionExtension owner) { _owner = owner; } public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture) { var enumerable = values[0]; var targetElement = (FrameworkElement)values[1]; var view = CollectionViewSource.GetDefaultView(enumerable); view.Filter = item => _owner.FilterInternal(targetElement.DataContext, item); return view; } public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture) { throw new NotSupportedException("Cannot convert back"); } } } I can see that the extension is instantiated and I can see it return the MultiBinding that is used by the Template. I also see the call to the InternalConverter.Convert method, which sees the expected parameters (I see the collection provided by the nested {Binding}) and is successfully able to retrieve the ICollectionView for the incoming collection. The only problem is that FilterInternal never gets called. The template is ultimately being used by a TreeView, if that's relevant. I haven't been able to figure out why the FilterInternal method is not being called and I was hoping somebody might be able to offer some insight.

    Read the article

  • MVVM in Task-It

    As I'm gearing up to write a post about dynamic XAP loading with MEF, I'd like to first talk a bit about MVVM, the Model-View-ViewModel pattern, as I will be leveraging this pattern in my future posts. Download Source Code Why MVVM? Your first question may be, "why do I need this pattern? I've been using a code-behind approach for years and it works fine." Well, you really don't have to make the switch to MVVM, but let me first explain some of the benefits I see for doing so. MVVM Benefits Testability - This is the one you'll probably hear the most about when it comes to MVVM. Moving most of the code from your code-behind to a separate view model class means you can now write unit tests against the view model without any knowledge of a view (UserControl). Multiple UIs - Let's just say that you've created a killer app, it's running in the browser, and maybe you've even made it run out-of-browser. Now what if your boss comes to you and says, "I heard about this new Windows Phone 7 device that is coming out later this year. Can you start porting the app to that device?". Well, now you have to create a new UI (UserControls, etc.) because you have a lot less screen real estate to work with. So what do you do, copy all of your existing UserControls, paste them, rename them, and then start changing the code? Hmm, that doesn't sound so good. But wait, if most of the code that makes your browser-based app tick lives in view model classes, now you can create new view (UserControls) for Windows Phone 7 that reference the same view model classes as your browser-based app. Page state - In Silverlight you're at some point going to be faced with the same issue you dealt with for years in ASP.NET, maintaining page state. Let's say a user hits your Products page, does some stuff (filters record, etc.), then leaves the page and comes back later. It would be best if the Products page was in the same state as when they left it right? Well, if you've thrown away your view (UserControl or Page) and moved off to another part of the UI, when you come back to Products you're probably going to re-instantiate your view...which will put it right back in the state it was when it started. Hmm, not good. Well, with a little help from MEF you can store the state in your view model class, MEF will keep that view model instance hanging around in memory, and then you simply rebind your view to the view model class. I made that sound easy, but it's actually a bit of work to properly store and restore the state. At least it can be done though, which will make your users a lot happier! I'll talk more about this in an upcoming blog post. No event handlers? Another nice thing about MVVM is that you can bind your UserControls to the view model, which may eliminate the need for event handlers in your code-behind. So instead of having a Click handler on a Button (or RadMenuItem), for example, you can now bind your control's Command property to a DelegateCommand in your view model (I'll talk more about Commands in an upcoming post). Instead of having a SelectionChanged event handler on your RadGridView you can now bind its SelectedItem property to a property in your view model, and each time the user clicks a row, the view model property's setter will be called. Now through the magic of binding we can eliminate the need for traditional code-behind based event handlers on our user interface controls, and the best thing is that the view model knows about everything that's going on...which means we can test things without a user interface. The brains of the operation So what we're seeing here is that the view is now just a dumb layer that binds to the view model, and that the view model is in control of just about everything, like what happens when a RadGridView row is selected, or when a RadComboBoxItem is selected, or when a RadMenuItem is clicked. It is also responsible for loading data when the page is hit, as well as kicking off data inserts, updates and deletions. Once again, all of this stuff can be tested without the need for a user interface. If the test works, then it'll work regardless of whether the user is hitting the browser-based version of your app, or the Windows Phone 7 version. Nice! The database Before running the code for this app you will need to create the database. First, create a database called MVVMProject in SQL Server, then run MVVMProject.sql in the MVVMProject/Database directory of your downloaded .zip file. This should give you a Task table with 3 records in it. When you fire up the solution you will also need to update the connection string in web.config to point to your database instead of IBM12\SQLSERVER2008. The code One note about this code is that it runs against the latest Silverlight 4 RC and WCF RIA Services code. Please see my first blog post about updating to the RC bits. Beta to RC - Part 1 At the top of this post is a link to a sample project that demonstrates a sample application with a Tasks page that uses the MVVM pattern. This is a simplified version of how I have implemented the Tasks page in the Task-It application. Youll notice that Tasks.xaml has very little code to it. Just a TextBlock that displays the page title and a ContentControl. <StackPanel>     <TextBlock Text="Tasks" Style="{StaticResource PageTitleStyle}"/>     <Rectangle Style="{StaticResource StandardSpacerStyle}"/>     <ContentControl x:Name="ContentControl1"/> </StackPanel> In List.xaml we have a RadGridView. Notice that the ItemsSource is bound to a property in the view model class call Tasks, SelectedItem is bound to a property in the view model called SelectedItem, and IsBusy is bound to a property in the view model called IsLoading. <Grid>     <telerikGridView:RadGridView ItemsSource="{Binding Tasks}" SelectedItem="{Binding SelectedItem, Mode=TwoWay}"                                  IsBusy="{Binding IsLoading}" AutoGenerateColumns="False" IsReadOnly="True" RowIndicatorVisibility="Collapsed"                IsFilteringAllowed="False" ShowGroupPanel="False">         <telerikGridView:RadGridView.Columns>             <telerikGridView:GridViewDataColumn Header="Name" DataMemberBinding="{Binding Name}" Width="3*"/>             <telerikGridView:GridViewDataColumn Header="Due" DataMemberBinding="{Binding DueDate}" DataFormatString="{}{0:d}" Width="*"/>         </telerikGridView:RadGridView.Columns>     </telerikGridView:RadGridView> </Grid> In Details.xaml we have a Save button that is bound to a property called SaveCommand in our view model. We also have a simple form (Im using a couple of controls here from Silverlight.FX for the form layout, FormPanel and Label simply because they make for a clean XAML layout). Notice that the FormPanel is also bound to the SelectedItem in the view model (the same one that the RadGridView is). The two form controls, the TextBox and RadDatePicker) are bound to the SelectedItem's Name and DueDate properties. These are properties of the Task object that WCF RIA Services creates. <StackPanel>     <Button Content="Save" Command="{Binding SaveCommand}" HorizontalAlignment="Left"/>     <Rectangle Style="{StaticResource StandardSpacerStyle}"/>     <fxui:FormPanel DataContext="{Binding SelectedItem}" Style="{StaticResource FormContainerStyle}">         <fxui:Label Text="Name:"/>         <TextBox Text="{Binding Name, Mode=TwoWay}"/>         <fxui:Label Text="Due:"/>         <telerikInput:RadDatePicker SelectedDate="{Binding DueDate, Mode=TwoWay}"/>     </fxui:FormPanel> </StackPanel> In the code-behind of the Tasks control, Tasks.xaml.cs, I created an instance of the view model class (TasksViewModel) in the constructor and set it as the DataContext for the control. The Tasks page will load one of two child UserControls depending on whether you are viewing the list of tasks (List.xaml) or the form for editing a task (Details.xaml). // Set the DataContext to an instance of the view model class var viewModel = new TasksViewModel(); DataContext = viewModel;   // Child user controls (inherit DataContext from this user control) List = new List(); // RadGridView Details = new Details(); // Form When the page first loads, the List is loaded into the ContentControl. // Show the RadGridView first ContentControl1.Content = List; In the code-behind we also listen for a couple of the view models events. The ItemSelected event will be fired when the user clicks on a record in the RadGridView in the List control. The SaveCompleted event will be fired when the user clicks Save in the Details control (the form). Here the view model is in control, and is letting the view know when something needs to change. // Listeners for the view model's events viewModel.ItemSelected += OnItemSelected; viewModel.SaveCompleted += OnSaveCompleted; The event handlers toggle the view between the RadGridView (List) and the form (Details). void OnItemSelected(object sender, RoutedEventArgs e) {     // Show the form     ContentControl1.Content = Details; }   void OnSaveCompleted(object sender, RoutedEventArgs e) {     // Show the RadGridView     ContentControl1.Content = List; } In TasksViewModel, we instantiate a DataContext object and a SaveCommand in the constructor. DataContext is a WCF RIA Services object that well use to retrieve the list of Tasks and to save any changes to a task. Ill talk more about this and Commands in future post, but for now think of the SaveCommand as an event handler that is called when the Save button in the form is clicked. DataContext = new DataContext(); SaveCommand = new DelegateCommand(OnSave); When the TasksViewModel constructor is called we also make a call to LoadTasks. This sets IsLoading to true (which causes the RadGridViews busy indicator to appear) and retrieves the records via WCF RIA Services.         public LoadOperation<Task> LoadTasks()         {             // Show the loading message             IsLoading = true;             // Get the data via WCF RIA Services. When the call has returned, called OnTasksLoaded.             return DataContext.Load(DataContext.GetTasksQuery(), OnTasksLoaded, false);         } When the data is returned, OnTasksLoaded is called. This sets IsLoading to false (which hides the RadGridViews busy indicator), and fires property changed notifications to the UI to let it know that the IsLoading and Tasks properties have changed. This property changed notification basically tells the UI to rebind. void OnTasksLoaded(LoadOperation<Task> lo) {     // Hide the loading message     IsLoading = false;       // Notify the UI that Tasks and IsLoading properties have changed     this.OnPropertyChanged(p => p.Tasks);     this.OnPropertyChanged(p => p.IsLoading); } Next lets look at the view models SelectedItem property. This is the one thats bound to both the RadGridView and the form. When the user clicks a record in the RadGridView its setter gets called (set a breakpoint and see what I mean). The other code in the setter lets the UI know that the SelectedItem has changed (so the form displays the correct data), and fires the event that notifies the UI that a selection has occurred (which tells the UI to switch from List to Details). public Task SelectedItem {     get { return _selectedItem; }     set     {         _selectedItem = value;           // Let the UI know that the SelectedItem has changed (forces it to re-bind)         this.OnPropertyChanged(p => p.SelectedItem);         // Notify the UI, so it can switch to the Details (form) page         NotifyItemSelected();     } } One last thing, saving the data. When the Save button in the form is clicked it fires the SaveCommand, which calls the OnSave method in the view model (once again, set a breakpoint to see it in action). public void OnSave() {     // Save the changes via WCF RIA Services. When the save is complete, call OnSaveCompleted.     DataContext.SubmitChanges(OnSaveCompleted, null); } In OnSave, we tell WCF RIA Services to submit any changes, which there will be if you changed either the Name or the Due Date in the form. When the save is completed, it calls OnSaveCompleted. This method fires a notification back to the UI that the save is completed, which causes the RadGridView (List) to show again. public virtual void OnSaveCompleted(SubmitOperation so) {     // Clear the item that is selected in the grid (in case we want to select it again)     SelectedItem = null;     // Notify the UI, so it can switch back to the List (RadGridView) page     NotifySaveCompleted(); } Did you know that DotNetSlackers also publishes .net articles written by top known .net Authors? We already have over 80 articles in several categories including Silverlight. Take a look: here.

    Read the article

  • When does the DataContext will open a connection to the DB?

    - by Eran Betzalel
    I am using L2S to access my MSSQL 2008 Express server. I would like to know when the DataContext will open a connection to the DB? and will it close the connection right after it opened it? For example: var dc = new TestDB(); // connection opened and closed? dc.SomeTable.InsertOnSubmit(obj); // connection opened and closed? foreach(var obj in dc.SomeTable.AsEnumerable()) // connection opened and closed? { ... // connection opened and closed? } dc.SubmitChanges(); // connection opened and closed?

    Read the article

  • Easy way to update models in your ASP.NET MVC business layer

    - by rajbk
    Brad Wilson just mentioned there is a static class ModelCopier that has a static method CopyModel(object from, object to) in the MVC Futures library. It uses reflection to match properties with the same name and compatible types. In short, instead of manually copying over properties as shown here: public void Save(EmployeeViewModel employeeViewModel){ var employee = (from emp in dataContext.Employees where emp.EmployeeID == employeeViewModel.EmployeeID select emp).SingleOrDefault(); if (employee != null) { employee.Address = employeeViewModel.Address; employee.Salary = employeeViewModel.Salary; employee.Title = employeeViewModel.Title; } dataContext.SubmitChanges();} you can use the method like so: public void Save(EmployeeViewModel employeeViewModel){ var employee = (from emp in dataContext.Employees where emp.EmployeeID == employeeViewModel.EmployeeID select emp).SingleOrDefault(); if (employee != null) { ModelCopier.CopyModel(employeeViewModel, employee); } dataContext.SubmitChanges();} Beautiful, isn’t it?

    Read the article

  • Why are my connections not closed even if I explicitly dispose of the DataContext?

    - by Chris Simpson
    I encapsulate my linq to sql calls in a repository class which is instantiated in the constructor of my overloaded controller. The constructor of my repository class creates the data context so that for the life of the page load, only one data context is used. In my destructor of the repository class I explicitly call the dispose of the DataContext though I do not believe this is necessary. Using performance monitor, if I watch my User Connections count and repeatedly load a page, the number increases once per page load. Connections do not get closed or reused (for about 20 minutes). I tried putting Pooling=false in my config to see if this had any effect but it did not. In any case with pooling I wouldn't expect a new connection for every load, I would expect it to reuse connections. I've tried putting a break point in the destructor to make sure the dispose is being hit and sure enough it is. So what's happening? Some code to illustrate what I said above: The controller: public class MyController : Controller { protected MyRepository rep; public MyController () { rep = new MyRepository(); } } The repository: public class MyRepository { protected MyDataContext dc; public MyRepository() { dc = getDC(); } ~MyRepository() { if (dc != null) { //if (dc.Connection.State != System.Data.ConnectionState.Closed) //{ // dc.Connection.Close(); //} dc.Dispose(); } } // etc } Note: I add a number of hints and context information to the DC for auditing purposes. This is essentially why I want one connection per page load

    Read the article

  • WPF and LINQ/SQL - how and where to keep track of changes?

    - by Groky
    I have a WPF application built using the MVVM pattern: My Models come from LINQ to SQL. I use the Repository Pattern to abstract away the DataContext. My ViewModels have a reference to a Model. Setting a property on the ViewModel causes that value to be written through to the Model. As you can see, my data is stored in my Model, and changes are therefore tracked by my DataContext. However, in this question I read: The guidelines from the MSDN documentation on the DataContext class are what I would recommend following: In general, a DataContext instance is designed to last for one "unit of work" however your application defines that term. A DataContext is lightweight and is not expensive to create. A typical LINQ to SQL application creates DataContext instances at method scope or as a member of short-lived classes that represent a logical set of related database operations. How do you track your changes? In your DataContext? In your ViewModel? Elsewhere?

    Read the article

  • Data layer refactoring

    - by Joey
    I've taken control of some entity framework code and am looking to refactor it. Before I do, I'd like to check my thoughts are correct and I'm not missing the entity-framework way of doing things. Example 1 - Subquery vs Join Here we have a one-to-many between As and Bs. Apart from the code below being hard to read, is it also inefficient? from a in dataContext.As where ((from b in dataContext.Bs where b.Text.StartsWith(searchText) select b.AId).Distinct()).Contains(a.Id) select a Would it be better, for example, to use the join and do something like this? from a in dataContext.As where a.Bs.Any(b => b.Text.StartsWith(searchText)) select a Example 2 - Explicit Joins vs Navigation Here we have a one-to-many between As and Bs and a one-to-many between Bs and Cs. from a in dataContext.As join b in dataContext.Bs on b.AId equals a.Id join c in dataContext.Cs on c.BId equals b.Id where c.SomeValue equals searchValue select a Is there a good reason to use explicit joins rather than navigating through the data model? For example: from a in dataContext.As where a.Bs.Any(b => b.Cs.Any(c => c.SomeValue == searchValue) select a

    Read the article

  • LINQ to SQL: To Attach or Not To Attach

    - by bradhe
    So I'm have a really hard time figuring out when I should be attaching to an object and when I shouldn't be attaching to an object. First thing's first, here is a small diagram of my (very simplified) object model. Edit: Okay, apparently I'm not allowed to post images...here you go: http://i.imgur.com/2ROFI.png In my DAL I create a new DataContext every time I do a data-related operation. Say, for instance, I want to save a new user. In my business layer I create a new user. var user = new User(); user.FirstName = "Bob"; user.LastName = "Smith"; user.Username = "bob.smith"; user.Password = StringUtilities.EncodePassword("MyPassword123"); user.Organization = someOrganization; // Assume that someOrganization was loaded and it's data context has been garbage collected. Now I want to go save this user. var userRepository = new RepositoryFactory.GetRepository<UserRepository>(); userRepository.Save(user); Neato! Here is my save logic: public void Save(User user) { if (!DataContext.Users.Contains(user)) { user.Id = Guid.NewGuid(); user.CreatedDate = DateTime.Now; user.Disabled = false; //DataContext.Organizations.Attach(user.Organization); DataContext.Users.InsertOnSubmit(user); } else { DataContext.Users.Attach(user); } DataContext.SubmitChanges(); // Finished here as well. user.Detach(); } So, here we are. You'll notice that I comment out the bit where the DataContext attachs to the organization. If I attach to the organization I get the following exception: NotSupportedException: An attempt has been made to Attach or Add an entity that is not new, perhaps having been loaded from another DataContext. This is not supported. Hmm, that doesn't work. Let me try it without attaching (i.e. comment out that line about attaching to the organization). DuplicateKeyException: Cannot add an entity with a key that is already in use. WHAAAAT? I can only assume this is trying to insert a new organization which is obviously false. So, what's the deal guys? What should I do? What is the proper approach? It seems like L2S makes this quite a bit harder than it should be...

    Read the article

  • How to set properties of a d:DesignInstance in XAML?

    - by Scott Bilas
    I'm using the new d:DesignInstance feature of the 4.0 series WPF tools. Works great! Only issue I'm having is: how can I set properties on the instance? Given something like this: <Grid d:DataContext="{d:DesignInstance plugin:SamplePendingChangesViewModel, IsDesignTimeCreatable=True}"/> How can I set properties on the viewmodel, aside from setting them in its default ctor or routing it through some other object initializer? I gave this a try but VS gives errors on compile "d:DataContext was not found": <Grid> <d:DataContext> <d:DesignInstance IsDesignTimeCreatable="True"> <plugin:SamplePendingChangesViewModel ActiveTagIndex="2"/> </d:DesignInstance> </d:DataContext> For the moment I'm going back to using a resource and 'd:DataContext={StaticResource SampleData}', where I can set the properties in the resource. Is there a way to do it via a d:DesignInstance?

    Read the article

  • Linq insert statement inserts nothing, does not fail either

    - by pietjepoeier
    I am trying to insert a new account in my Acccounts table with linq. I tried using the EntityModel and Linq2Sql. I get no insert into my database nor an exception of any kind. public static Linq2SQLDataContext dataContext { get { return new Linq2SQLDataContext(); } } try { //EntityModel Accounts acc = Accounts.CreateAccounts(0, Voornaam, Straat, Huisnummer, Stad, Land, 15, EmailReg, Password1); Entities.AddToAccounts(acc); Entities.SaveChanges(); //Linq 2 SQL Account account = new Account { City = Stad, Country = Land, EmailAddress = EmailReg, Name = Voornaam, Password = Password1, Street = Straat, StreetNr = Huisnummer, StreetNrAdd = Toevoeging, Points = 25 }; dataContext.Accounts.InsertOnSubmit(account); var conf = dataContext.ChangeConflicts; // No changeConflicts ChangeSet set = dataContext.GetChangeSet(); // 0 inserts, 0 updates, 0 deletes try { dataContext.SubmitChanges(); } catch (Exception ex) { } } catch (EntityException ex) { }

    Read the article

  • linq-to-sql "an attempt has been made to attach or add an entity that is not new"?

    - by Curtis White
    I've been getting several errors: cannot add an entity with a key that is already in use An attempt has been made to attach or add an entity that is not new, perhaps having been loaded from another datacontext In case 1, this stems from trying to set the key for an entity versus the entity. In case 2, I'm not attaching an entity but I am doing this: MyParent.Child = EntityFromOtherDataContext; I've been using using the pattern of wrap everything with a using datacontext. In my case, I am using this in a web forms scenario, and obviously moving the datacontext object to a class wide member variables solves this. My questions are thus 2 fold: How can I get rid of these errors and not have to structure my program in an odd way or pass the datacontext around while keeping the local-wrap pattern? I assume I could make another hit to the database but that seems very inefficient. Would most people recommend that moving the datacontext to the class wide scope is desirable for web pages?

    Read the article

  • DI with disposable objects

    - by sunnychaganty
    Suppose my repository class looks like this: class myRepository : IDisposable{ private DataContext _context; public myRepository(DataContext context){ _context = context; } public void Dispose(){ // to do: implement dispose of DataContext } } now, I am using Unity to control the lifetime of my repository & the data context & configured the lifetimes as: DataContext - singleton myRepository - create a new instance each time Does this mean that I should not be implementing the IDisposable on the repository to clean up the DataContext? Any guidance on such items?

    Read the article

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