none
"The type 'System.Data.Services.Client.DataServiceResponsePreference' has no settable properties." On Save data with WCF DataService using Binding List RRS feed

  • Question

  • Hello

    I am using WCF DataService with Entity framework.

    At at client app I have added service reference. So that My dataContext (NorthwindEntities) can be reflacted at client side.

    I have to use BindingList . Plus I have property of DataContext at BindingList side which I am setting.

    Following is my code

    public class OrderBindingList : BindingList<Order> { #region Constructor /// <summary> /// Initializes a new instance of the <see cref="AvailableStockBindingList" /> class. /// </summary> /// <param name="list"> an IList object.</param> public OrderBindingList(IList<Order> list) : base(list) { } #endregion #region Public Properties /// <summary> /// Gets or sets a value for DataContext. /// </summary> [DoNotSerialize] public ServiceReference1.NorthwindEntities DataContext { get; set; } #endregion } public partial class MainWindow : Window { public OrderBindingList mibl { get; set; } public MainWindow() { InitializeComponent(); ServiceReference1.NorthwindEntities dc = new ServiceReference1.NorthwindEntities(new Uri("http://localhost:50474/WcfDataService1.svc")); mibl = new OrderBindingList(dc.Orders.ToList()); mibl.DataContext = dc ; /// If I set this then ///error comes. I must set this. Order mi = mibl.FirstOrDefault(); if (mi != null) { mi.Freight += 1; } dc.UpdateObject(mi); dc.SaveChanges(); /// Here error comes } }

    /// Following is my Order class code which is generated. I have added one property to Order generated class.

    /// Here I am sharing some code which I added to it

     [global::System.Data.Services.Common.EntitySetAttribute("Orders")]
        [global::System.Data.Services.Common.DataServiceKeyAttribute("OrderID")]
        public partial class Order : global::System.ComponentModel.INotifyPropertyChanged, global::System.ComponentModel.INotifyPropertyChanging
        {
           
            object wait = new object();
            private NorthwindEntities _DataContext;
            [DoNotSerialize]
            public NorthwindEntities DataContext
            {
                set { _DataContext = value; }
                get
                {
                    object value;
                    if (_DataContext != null)
                        return _DataContext;
                    else
                    {
                        INotifyPropertyChanging obj = this;
                        FieldInfo fEvent = (obj.GetType()).GetField("PropertyChanging", BindingFlags.NonPublic | BindingFlags.Instance);
                        MulticastDelegate dEvent = (MulticastDelegate)fEvent.GetValue(obj);
                        if (dEvent != null)
                        {
                            Delegate[] onChangingHandlers = dEvent.GetInvocationList();

                            foreach (Delegate handler in onChangingHandlers)
                            {
                                if (handler.Target.GetType().Name == "StandardChangeTracker")
                                {
                                    object tracker = handler.Target;
                                    object services = tracker.GetType().GetField("services", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(tracker);

                                    global::System.Data.Services.Client.DataServiceContext context = services.GetType().GetProperty("Context").GetValue(services, null) as global::System.Data.Services.Client.DataServiceContext;
                                    if (context is NorthwindEntities)
                                    {
                                        _DataContext = (NorthwindEntities)context;
                                        return _DataContext;
                                    }
                                }
                            }
                        }
                        else
                        {
                            INotifyPropertyChanged objChanged = this;
                            FieldInfo finfoPropertyChanged = (objChanged.GetType()).GetField("PropertyChanged", BindingFlags.NonPublic | BindingFlags.Instance);
                            MulticastDelegate mDelegate = (MulticastDelegate)finfoPropertyChanged.GetValue(objChanged);
                            if (mDelegate != null)
                            {
                                Delegate[] onChangedHandler = mDelegate.GetInvocationList();
                                object target = onChangedHandler.First().Target;
                                var data = target.GetType().GetField("data", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
                                IBindingList lst = target as IBindingList;
                                if (lst == null) return null;
                                global::System.Data.Services.Client.DataServiceContext context = target.GetType().GetProperty("DataContext").GetValue(target, null) as global::System.Data.Services.Client.DataServiceContext;
                                ////global::System.Data.Services.Client.DataServiceContext context = DataContextHelper.GetDataContext(lst);
                                if (context is NorthwindEntities)
                                {
                                    _DataContext = (NorthwindEntities)context;
                                    return _DataContext; ;
                                }
                            }
                        }
                        return null;
                    }
                }
            }

    /// .... Other code as it is


    At the time of saving following error coming:

    "The type 'System.Data.Services.Client.DataServiceResponsePreference' has no settable properties."

      at System.Data.Services.Client.SaveResult.HandleResponse()
       at System.Data.Services.Client.BaseSaveResult.EndRequest()
       at System.Data.Services.Client.DataServiceContext.SaveChanges(SaveChangesOptions options)
       at System.Data.Services.Client.DataServiceContext.SaveChanges()
       at EntityFWBindingListCHK.MainWindow..ctor() in d:\projects\EntityFWBindingListCHK\EntityFWBindingListCHK\MainWindow.xaml.cs:line 39

    Can any one please guide me how to solve this issue?

    Regards

    Vipul

    Thursday, December 24, 2015 5:41 AM

Answers

  • The whole WPF MVVM solution is using the pattern of..

    UI

    MVVM

    Service Layer

    WCF Web service

    BLL

    DAL

    EF Model

    The only thing the VM(s) know about is the Service Layer and the DTO.

    I can't help you with Odata and EF, because I don't use it.

    I consider what you are doing is the wrong approach.

    http://www.vbforums.com/showthread.php?540421-Tutorial-An-Introduction-to-the-ADO-NET-Entity-Framework

    I took the above tutorial based on EF used in Windows form solution

    and made it use n-tier using WCF Web service.

    All I can do is lead you to the water, but I can't make you drink

    -----------------------------------------------------------

    using System.Globalization; using System.Windows; using System.Windows.Markup; using System; using DemoWPFApp.ViewModel; using Services; namespace DemoWPFApp { public partial class App : Application { static App() { // This code is used to test the app when using other cultures. // //System.Threading.Thread.CurrentThread.CurrentCulture = // System.Threading.Thread.CurrentThread.CurrentUICulture = // new System.Globalization.CultureInfo("it-IT"); // Ensure the current culture passed into bindings is the OS culture. // By default, WPF uses en-US as the culture, regardless of the system settings. // FrameworkElement.LanguageProperty.OverrideMetadata( typeof(FrameworkElement), new FrameworkPropertyMetadata(XmlLanguage.GetLanguage(CultureInfo.CurrentCulture.IetfLanguageTag))); } protected override void OnStartup(StartupEventArgs e) { base.OnStartup(e); MainWindow window = new MainWindow(); // Create the ViewModel to which // the main window binds. var viewModel = new MainWindowViewModel(TheService1.Instance); // When the ViewModel asks to be closed, // close the window. EventHandler handler = null; handler = delegate { viewModel.RequestClose -= handler; window.Close(); }; viewModel.RequestClose += handler; // Allow all controls in the window to // bind to the ViewModel by setting the // DataContext, which propagates down // the element tree. window.DataContext = viewModel; window.Show(); } } } namespace DemoWPFApp { public partial class MainWindow : System.Windows.Window { public MainWindow() { InitializeComponent(); } } } using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.ComponentModel; using System.Diagnostics; using System.Linq; using System.Windows.Data; using DemoWPFApp; using DemoWPFApp.Properties; using DemoWPFApp.ViewModel; using Services.IServices; namespace DemoWPFApp.ViewModel { /// <summary> /// The ViewModel for the application's main window. /// </summary> public class MainWindowViewModel : WorkspaceViewModel { #region Fields ReadOnlyCollection<CommandViewModel> _commands; ObservableCollection<WorkspaceViewModel> _workspaces; private readonly IService1 _mService; #endregion // Fields #region Constructor public MainWindowViewModel(IService1 theService) { _mService = theService; base.DisplayName = Strings.MainWindowViewModel_DisplayName; } #endregion // Constructor #region Commands /// <summary> /// Returns a read-only list of commands /// that the UI can display and execute. /// </summary> public ReadOnlyCollection<CommandViewModel> Commands { get { if (_commands == null) { List<CommandViewModel> cmds = CreateCommands(); _commands = new ReadOnlyCollection<CommandViewModel>(cmds); } return _commands; } } public List<CommandViewModel> CreateCommands() { return new List<CommandViewModel> { new CommandViewModel( Strings.MainWindowViewModel_Command_PayRollView, new RelayCommand(param => ShowPayRoll())), new CommandViewModel( Strings.MainWindowViewModel_Command_AuthorView, new RelayCommand(param => ShowAuthor())), new CommandViewModel( Strings.MainWindowViewModel_Command_ArticleView, new RelayCommand(param => ShowArticle())) }; } #endregion // Commands #region Workspaces /// <summary> /// Returns the collection of available workspaces to display. /// A 'workspace' is a ViewModel that can request to be closed. /// </summary> public ObservableCollection<WorkspaceViewModel> Workspaces { get { if (_workspaces == null) { _workspaces = new ObservableCollection<WorkspaceViewModel>(); _workspaces.CollectionChanged += OnWorkspacesChanged; } return _workspaces; } } void OnWorkspacesChanged(object sender, NotifyCollectionChangedEventArgs e) { if (e.NewItems != null && e.NewItems.Count != 0) foreach (WorkspaceViewModel workspace in e.NewItems) workspace.RequestClose += OnWorkspaceRequestClose; if (e.OldItems != null && e.OldItems.Count != 0) foreach (WorkspaceViewModel workspace in e.OldItems) workspace.RequestClose -= this.OnWorkspaceRequestClose; } void OnWorkspaceRequestClose(object sender, EventArgs e) { WorkspaceViewModel workspace = sender as WorkspaceViewModel; workspace.Dispose(); this.Workspaces.Remove(workspace); } #endregion // Workspaces #region Private Helpers public void ShowPayRoll() { var workspace = Workspaces.FirstOrDefault(vm => vm is PayRollViewModel) as PayRollViewModel; if (workspace == null) { workspace = new PayRollViewModel(_mService); Workspaces.Add(workspace); } SetActiveWorkspace(workspace); } public void ShowAuthor() { var workspace = Workspaces.FirstOrDefault(vm => vm is AuthorViewModel) as AuthorViewModel; if (workspace == null) { workspace = new AuthorViewModel(_mService); Workspaces.Add(workspace); } SetActiveWorkspace(workspace); } public void ShowArticle() { var workspace = Workspaces.FirstOrDefault(vm => vm is ArticleViewModel) as ArticleViewModel; if (workspace == null) { workspace = new ArticleViewModel(_mService); Workspaces.Add(workspace); } SetActiveWorkspace(workspace); } void SetActiveWorkspace(WorkspaceViewModel workspace) { Debug.Assert(this.Workspaces.Contains(workspace)); ICollectionView collectionView = CollectionViewSource.GetDefaultView(this.Workspaces); if (collectionView != null) collectionView.MoveCurrentTo(workspace); } #endregion // Private Helpers } } using System.Linq; using System.Windows.Input; using DemoWPFApp.Properties; using Services.IServices; using System.Collections.Generic; using BLL.DTO; namespace DemoWPFApp.ViewModel { public class ArticleViewModel : WorkspaceViewModel { private readonly IService1 mService; private int idx; private string _articleid; private string _title; private string _body; private DTOArticle _dtoarticle; private List<DTOArticle> _articles; private RelayCommand _updateCommand; private RelayCommand _addCommand; private RelayCommand _saveCommand; private RelayCommand _deleteCommand; private RelayCommand _moveLastCommand; private RelayCommand _movePrevCommand; private RelayCommand _moveNextCommand; private RelayCommand _moveFirstCommand; private RelayCommand _clearCommand; public ArticleViewModel(IService1 theService) { mService = theService; _articles = mService.GetArticles(); _dtoarticle = mService.GetArticleTop1(); idx = 0; PopulateProperties(_dtoarticle); base.DisplayName = Strings.ArticleViewModel_DisplayName; } public string ArticleID { get { return _articleid; } set { _articleid = value; base.OnPropertyChanged("ArticleID"); } } public string Title { get { return _title; } set { _title = value; base.OnPropertyChanged("Title"); } } public string Body { get { return _body; } set { _body = value; base.OnPropertyChanged("Body"); } } public override string DisplayName { get { { return Strings.ArticleViewModel_DisplayName; } } } public ICommand UpdateCommand { get { if (_updateCommand == null) { _updateCommand = new RelayCommand( param => Update(), param => CanUpdate ); } return _updateCommand; } } public ICommand AddCommand { get { if (_addCommand == null) { _addCommand = new RelayCommand( param => Add(), param => CanAdd ); } return _addCommand; } } public ICommand SaveCommand { get { if (_saveCommand == null) { _saveCommand = new RelayCommand( param => Save(), param => CanSave ); } return _saveCommand; } } public ICommand DeleteCommand { get { if (_deleteCommand == null) { _deleteCommand = new RelayCommand( param => Delete(), param => CanDelete ); } return _deleteCommand; } } public ICommand ClearCommand { get { if (_clearCommand == null) { _clearCommand = new RelayCommand( param => Clear(), param => CanClear ); } return _clearCommand; } } public ICommand MoveLastCommand { get { if (_moveLastCommand == null) { _moveLastCommand = new RelayCommand( param => MoveLast(), param => CanMove ); } return _moveLastCommand; } } public ICommand MoveFirstCommand { get { if (_moveFirstCommand == null) { _moveFirstCommand = new RelayCommand( param => MoveFirst(), param => CanMove ); } return _moveFirstCommand; } } public ICommand MovePrevCommand { get { if (_movePrevCommand == null) { _movePrevCommand = new RelayCommand( param => MovePrev(), param => CanMove ); } return _movePrevCommand; } } public ICommand MoveNextCommand { get { if (_moveNextCommand == null) { _moveNextCommand = new RelayCommand( param => MoveNext(), param => CanMove ); } return _moveNextCommand; } } private void PopulateProperties(DTOArticle article) { ArticleID = article.ArticleID.ToString(); Title = article.Title; Body = article.Body; } private void PopulateProperties(List<DTOArticle> articles, int idxx) { ArticleID = articles[idxx].ArticleID.ToString(); Title = articles[idxx].Title; Body = articles[idxx].Body; } private void Update() { if(_articles != null) { _articles[idx].Title = Title; _articles[idx].Body = Body; _articles[idx].IsUpdate = true; } base.OnPropertyChanged("DisplayName"); } private void Add() { if (_articles != null) { if (Title != string.Empty && Body != string.Empty && ArticleID == "Article not saved yet.") { var dto = new DTOArticle {ArticleID = -1, AuthorID = 1, Title = Title, Body = Body, IsUpdate = false}; _articles.Add(dto); idx = _articles.Count - 1; } } base.OnPropertyChanged("DisplayName"); } private void Save() { if (_articles != null) { var atleastonearticle = (from a in _articles.Where(a => a.IsUpdate || a.ArticleID == -1) select a).FirstOrDefault(); if (atleastonearticle != null) { _articles = mService.SaveArticles(_articles); PopulateProperties(_articles, idx); } } base.OnPropertyChanged("DisplayName"); } private void Delete() { if (_articles.Count > 0) { var article = _articles[idx]; mService.DeleteArticle(article); _articles.RemoveAt(idx); idx = 0; PopulateProperties(_articles, idx); } } private void MoveLast() { if (_articles != null) { idx = _articles.Count - 1; PopulateProperties(_articles, idx); } base.OnPropertyChanged("DisplayName"); } private void MovePrev() { if (_articles != null) { if (idx == 0) { PopulateProperties(_articles, idx); } else { idx -= 1; PopulateProperties(_articles, idx); } } base.OnPropertyChanged("DisplayName"); } private void MoveNext() { if (_articles != null) { if (idx == _articles.Count - 1) { PopulateProperties(_articles, idx); } else { idx += 1; PopulateProperties(_articles, idx); } } base.OnPropertyChanged("DisplayName"); } private void MoveFirst() { if (_articles != null) { idx = 0; PopulateProperties(_articles, idx); } base.OnPropertyChanged("DisplayName"); } private void Clear() { Title = ""; Body = ""; ArticleID = "Article not saved yet."; } bool CanUpdate { get { return true; } } bool CanAdd { get { return true; } } bool CanDelete { get { return true; } } bool CanSave { get { return true; } } bool CanMove { get { return true; } } bool CanClear { get { return true; } } } }


    Friday, December 25, 2015 11:18 AM

All replies

  • Where did you get this code to even come up with something like what you are doing?
    Thursday, December 24, 2015 7:40 AM
  • Hello

    At every entity we have datacontext property which is got from its binding list. Everybinding list we set datacontext property. So this is our mechanism. 

    We try to modify the files which were reflacted to client side due to service reference. For that we were checking some of our mechanism But here we are getting this kind of error & not getting how to solve this.

    We also manage WritingEntity event at DataContextService (Northwindentities at client side which is reflacted due to service reference) to ignore property with particular attribute. But Here in this case it is giving error prior the WritingEntity event call. 

    Is there any clue to manage the issue?

    Regards

    Vipul


    Thursday, December 24, 2015 9:16 AM
  • I find it questionable as to what you are doing. And IMHO, the client should never be in direct contact with the ORM Odata or not. The client should never know about the EF entities, and that is why there are such objects as DTO(s). 

    https://en.wikipedia.org/wiki/Separation_of_concerns

    https://msdn.microsoft.com/en-us/library/ee658090.aspx?f=255&MSPPError=-2147217396

    https://en.wikipedia.org/wiki/Data_transfer_object

    http://www.mindscapehq.com/documentation/lightspeed/Building-Distributed-Applications-/Building-WCF-Services-using-Data-Transfer-Objects

    The client should know about the DTO(s) and not the EF entities.

    Thursday, December 24, 2015 5:06 PM
  • Hello

    Thank you for your quick response.

    Actualy Suppose there is Order & OrderDetails with one to many relations.

    At our entity Order we want to create OrderDetailBindingList. In short DataContext property is necessary.

    With simple LinqToSql it is possible.

    Even with Entity Framework with WCF DataService if I use Orders object to modify like

    dc.Orders.first().Freight +=1;

    Then It will work. In that case DataContext property will not give any issue.

    I have used WritingEntity event at datacontext at client side which will remove property from request who has particular attribute (I got this solution online). 

    But If I use bindingList then issue comming.

    So two things I want to ask:

    1) Is this possible or not with bindingList.

    2) If not possible then Why it is not possible? & why it was working If I use Table 

    dc.Orders.First().Freight +=1;

    To update then it will work. At that time it will work.

    If I use table object then at the time I call savechanges it will not call get of DataContext property But call writingEntity event from which I am removing properties.. But If I use bindingList then at time of savechanges() it will call getter of DataContext property. Here before WritingEntity call error comes.

    Here I am sharing what I have written at my generated datacontext class to ignore properties at time of saving.

    public partial class NorthwindEntities : global::System.Data.Services.Client.DataServiceContext
        {
            /// <summary>
            /// Initialize a new NorthwindEntities object.
            /// </summary>
            [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]
            public NorthwindEntities(global::System.Uri serviceRoot) : 
                    base(serviceRoot, global::System.Data.Services.Common.DataServiceProtocolVersion.V3)
            {
                //this.ResolveName = new global::System.Func<global::System.Type, string>(this.ResolveNameFromType);
                //this.ResolveType = new global::System.Func<string, global::System.Type>(this.ResolveTypeFromName);
                //this.OnContextCreated();
                this.SaveChangesDefaultOptions = System.Data.Services.Client.SaveChangesOptions.ReplaceOnUpdate;
                //this.UsePostTunneling = true;
                //this.IgnoreResourceNotFoundException = true;
                this.WritingEntity += NorthwindEntities_WritingEntity;
                //this.SendingRequest2 += NorthwindEntities_SendingRequest2;
                //this.SendingRequest += NorthwindEntities_SendingRequest;
                this.ReadingEntity += NorthwindEntities_ReadingEntity;
                this.ResolveName = new global::System.Func<global::System.Type, string>(this.ResolveNameFromType);
                this.ResolveType = new global::System.Func<string, global::System.Type>(this.ResolveTypeFromName);
                this.OnContextCreated();
            }

            private void NorthwindEntities_ReadingEntity(object sender, System.Data.Services.Client.ReadingWritingEntityEventArgs e)
            {
                if (e.Data.GetNamespaceOfPrefix("m") != null)
                {
                    // e.Data gives you the XElement for the Serialization of the Entity 
                    //Using XLinq  , you can  add/Remove properties to the element Payload  
                    XName xnEntityProperties = XName.Get("properties", e.Data.GetNamespaceOfPrefix("m").NamespaceName);
                    XElement xePayload = null;
                    foreach (PropertyInfo property in e.Entity.GetType().GetProperties())
                    {
                        object[] doNotSerializeAttributes = property.GetCustomAttributes(typeof(DoNotSerializeAttribute), false);
                        if (doNotSerializeAttributes.Length > 0)
                        {
                            if (xePayload == null)
                            {
                                xePayload = e.Data.Descendants().Where<XElement>(xe => xe.Name == xnEntityProperties).First<XElement>();
                            }
                            //The XName of the property we are going to remove from the payload
                            XName xnProperty = XName.Get(property.Name, e.Data.GetNamespaceOfPrefix("d").NamespaceName);
                            //Get the Property of the entity  you don't want sent to the server
                            foreach (XElement xeRemoveThisProperty in xePayload.Descendants(xnProperty).ToList())
                            {
                                //Remove this property from the Payload sent to the server 
                                xeRemoveThisProperty.Remove();
                            }
                        }
                    }
                }
            }

            void NorthwindEntities_WritingEntity(object sender, System.Data.Services.Client.ReadingWritingEntityEventArgs e)
            {
                XName xnEntityProperties = XName.Get("properties", e.Data.GetNamespaceOfPrefix("m").NamespaceName);
                XElement xePayload = null;
                foreach (PropertyInfo property in e.Entity.GetType().GetProperties())
                {
                    object[] doNotSerializeAttributes = property.GetCustomAttributes(typeof(DoNotSerializeAttribute), false);
                    if (doNotSerializeAttributes.Length > 0)
                    {
                        if (xePayload == null)
                        {
                            xePayload = e.Data.Descendants().Where<XElement>(xe => xe.Name == xnEntityProperties).First<XElement>();
                        }
                        //The XName of the property we are going to remove from the payload
                        XName xnProperty = XName.Get(property.Name, e.Data.GetNamespaceOfPrefix("d").NamespaceName);
                        //Get the Property of the entity  you don't want sent to the server
                        foreach (XElement xeRemoveThisProperty in xePayload.Descendants(xnProperty).ToList())
                        {
                            //Remove this property from the Payload sent to the server 
                            xeRemoveThisProperty.Remove();
                        }
                    }
                }
            }

    .... /// Other code as it is.

    Can you please explain with more detail?

    Regards

    Vipul


    Friday, December 25, 2015 3:44 AM
  • Actualy Suppose there is Order & OrderDetails with one to many relations.

    So why can't you have a DtoOrder with a List<DtoOrderDetail> OrderDetails within DtoOrder? How is that not the same relationship of Order Detail objects that belong to the parent Order object?

    With simple LinqToSql it is possible.

    The big brother ORM EF is not Linq-2-SQL.

    Even with Entity Framework with WCF DataService if I use Orders object to modify like

    Your problem is that you are not using Separation of Duties by using EF directly at the form level instead of using MVVM in WPF in  a SoD. 

    http://www.codeproject.com/Articles/228214/Understanding-Basics-of-UI-Design-Pattern-MVC-MVP

    Your second problem is that you are not using SoC where interaction with EF is done at the DAL using the Repository and Unit of Work or Data Access Object pattern.

    https://en.wikipedia.org/wiki/Separation_of_concerns

    <copied>

     Layered designs in information systems are another embodiment of separation of concerns (e.g., presentation layer, business logic layer, data access layer, persistence layer).

    The value of separation of concerns is simplifying development and maintenance of computer programs. When concerns are well-separated, individual sections can be reused, as well as developed and updated independently. Of special value is the ability to later improve or modify one section of code without having to know the details of other sections, and without having to make corresponding changes to those sections.

    <end>

    I'll state it to you one more time. The UI should be unaware that EF even exist.  But for some reason,  you are using Odata and EF right up there at the UI,  a no no.

    I don't use Odata for anything.

    UI

    MVP, MVVM, MVPVM or MVC

    Service Layer

    WCF Web service

    BLL

    DAL

    EF Model

    Friday, December 25, 2015 6:00 AM
  • Hello

    Thank you for the quick response.

    1) Can you please tell exact problem why it is giving error at the time of saving record?

    2) When service reference added entities automatically created at client side. So I just hav emodified it.

    3) According to following suggesation I am following this pattern.

    https://social.msdn.microsoft.com/Forums/vstudio/en-US/2229c668-0ae7-4835-911b-b82b48465ce0/split-view-from-viewmodel-model-with-wpf-application?forum=wpf

    Can you please tell me exact problem & if possible then solution for it?

    Regards

    Vipul

    Friday, December 25, 2015 9:59 AM
  • The whole WPF MVVM solution is using the pattern of..

    UI

    MVVM

    Service Layer

    WCF Web service

    BLL

    DAL

    EF Model

    The only thing the VM(s) know about is the Service Layer and the DTO.

    I can't help you with Odata and EF, because I don't use it.

    I consider what you are doing is the wrong approach.

    http://www.vbforums.com/showthread.php?540421-Tutorial-An-Introduction-to-the-ADO-NET-Entity-Framework

    I took the above tutorial based on EF used in Windows form solution

    and made it use n-tier using WCF Web service.

    All I can do is lead you to the water, but I can't make you drink

    -----------------------------------------------------------

    using System.Globalization; using System.Windows; using System.Windows.Markup; using System; using DemoWPFApp.ViewModel; using Services; namespace DemoWPFApp { public partial class App : Application { static App() { // This code is used to test the app when using other cultures. // //System.Threading.Thread.CurrentThread.CurrentCulture = // System.Threading.Thread.CurrentThread.CurrentUICulture = // new System.Globalization.CultureInfo("it-IT"); // Ensure the current culture passed into bindings is the OS culture. // By default, WPF uses en-US as the culture, regardless of the system settings. // FrameworkElement.LanguageProperty.OverrideMetadata( typeof(FrameworkElement), new FrameworkPropertyMetadata(XmlLanguage.GetLanguage(CultureInfo.CurrentCulture.IetfLanguageTag))); } protected override void OnStartup(StartupEventArgs e) { base.OnStartup(e); MainWindow window = new MainWindow(); // Create the ViewModel to which // the main window binds. var viewModel = new MainWindowViewModel(TheService1.Instance); // When the ViewModel asks to be closed, // close the window. EventHandler handler = null; handler = delegate { viewModel.RequestClose -= handler; window.Close(); }; viewModel.RequestClose += handler; // Allow all controls in the window to // bind to the ViewModel by setting the // DataContext, which propagates down // the element tree. window.DataContext = viewModel; window.Show(); } } } namespace DemoWPFApp { public partial class MainWindow : System.Windows.Window { public MainWindow() { InitializeComponent(); } } } using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.ComponentModel; using System.Diagnostics; using System.Linq; using System.Windows.Data; using DemoWPFApp; using DemoWPFApp.Properties; using DemoWPFApp.ViewModel; using Services.IServices; namespace DemoWPFApp.ViewModel { /// <summary> /// The ViewModel for the application's main window. /// </summary> public class MainWindowViewModel : WorkspaceViewModel { #region Fields ReadOnlyCollection<CommandViewModel> _commands; ObservableCollection<WorkspaceViewModel> _workspaces; private readonly IService1 _mService; #endregion // Fields #region Constructor public MainWindowViewModel(IService1 theService) { _mService = theService; base.DisplayName = Strings.MainWindowViewModel_DisplayName; } #endregion // Constructor #region Commands /// <summary> /// Returns a read-only list of commands /// that the UI can display and execute. /// </summary> public ReadOnlyCollection<CommandViewModel> Commands { get { if (_commands == null) { List<CommandViewModel> cmds = CreateCommands(); _commands = new ReadOnlyCollection<CommandViewModel>(cmds); } return _commands; } } public List<CommandViewModel> CreateCommands() { return new List<CommandViewModel> { new CommandViewModel( Strings.MainWindowViewModel_Command_PayRollView, new RelayCommand(param => ShowPayRoll())), new CommandViewModel( Strings.MainWindowViewModel_Command_AuthorView, new RelayCommand(param => ShowAuthor())), new CommandViewModel( Strings.MainWindowViewModel_Command_ArticleView, new RelayCommand(param => ShowArticle())) }; } #endregion // Commands #region Workspaces /// <summary> /// Returns the collection of available workspaces to display. /// A 'workspace' is a ViewModel that can request to be closed. /// </summary> public ObservableCollection<WorkspaceViewModel> Workspaces { get { if (_workspaces == null) { _workspaces = new ObservableCollection<WorkspaceViewModel>(); _workspaces.CollectionChanged += OnWorkspacesChanged; } return _workspaces; } } void OnWorkspacesChanged(object sender, NotifyCollectionChangedEventArgs e) { if (e.NewItems != null && e.NewItems.Count != 0) foreach (WorkspaceViewModel workspace in e.NewItems) workspace.RequestClose += OnWorkspaceRequestClose; if (e.OldItems != null && e.OldItems.Count != 0) foreach (WorkspaceViewModel workspace in e.OldItems) workspace.RequestClose -= this.OnWorkspaceRequestClose; } void OnWorkspaceRequestClose(object sender, EventArgs e) { WorkspaceViewModel workspace = sender as WorkspaceViewModel; workspace.Dispose(); this.Workspaces.Remove(workspace); } #endregion // Workspaces #region Private Helpers public void ShowPayRoll() { var workspace = Workspaces.FirstOrDefault(vm => vm is PayRollViewModel) as PayRollViewModel; if (workspace == null) { workspace = new PayRollViewModel(_mService); Workspaces.Add(workspace); } SetActiveWorkspace(workspace); } public void ShowAuthor() { var workspace = Workspaces.FirstOrDefault(vm => vm is AuthorViewModel) as AuthorViewModel; if (workspace == null) { workspace = new AuthorViewModel(_mService); Workspaces.Add(workspace); } SetActiveWorkspace(workspace); } public void ShowArticle() { var workspace = Workspaces.FirstOrDefault(vm => vm is ArticleViewModel) as ArticleViewModel; if (workspace == null) { workspace = new ArticleViewModel(_mService); Workspaces.Add(workspace); } SetActiveWorkspace(workspace); } void SetActiveWorkspace(WorkspaceViewModel workspace) { Debug.Assert(this.Workspaces.Contains(workspace)); ICollectionView collectionView = CollectionViewSource.GetDefaultView(this.Workspaces); if (collectionView != null) collectionView.MoveCurrentTo(workspace); } #endregion // Private Helpers } } using System.Linq; using System.Windows.Input; using DemoWPFApp.Properties; using Services.IServices; using System.Collections.Generic; using BLL.DTO; namespace DemoWPFApp.ViewModel { public class ArticleViewModel : WorkspaceViewModel { private readonly IService1 mService; private int idx; private string _articleid; private string _title; private string _body; private DTOArticle _dtoarticle; private List<DTOArticle> _articles; private RelayCommand _updateCommand; private RelayCommand _addCommand; private RelayCommand _saveCommand; private RelayCommand _deleteCommand; private RelayCommand _moveLastCommand; private RelayCommand _movePrevCommand; private RelayCommand _moveNextCommand; private RelayCommand _moveFirstCommand; private RelayCommand _clearCommand; public ArticleViewModel(IService1 theService) { mService = theService; _articles = mService.GetArticles(); _dtoarticle = mService.GetArticleTop1(); idx = 0; PopulateProperties(_dtoarticle); base.DisplayName = Strings.ArticleViewModel_DisplayName; } public string ArticleID { get { return _articleid; } set { _articleid = value; base.OnPropertyChanged("ArticleID"); } } public string Title { get { return _title; } set { _title = value; base.OnPropertyChanged("Title"); } } public string Body { get { return _body; } set { _body = value; base.OnPropertyChanged("Body"); } } public override string DisplayName { get { { return Strings.ArticleViewModel_DisplayName; } } } public ICommand UpdateCommand { get { if (_updateCommand == null) { _updateCommand = new RelayCommand( param => Update(), param => CanUpdate ); } return _updateCommand; } } public ICommand AddCommand { get { if (_addCommand == null) { _addCommand = new RelayCommand( param => Add(), param => CanAdd ); } return _addCommand; } } public ICommand SaveCommand { get { if (_saveCommand == null) { _saveCommand = new RelayCommand( param => Save(), param => CanSave ); } return _saveCommand; } } public ICommand DeleteCommand { get { if (_deleteCommand == null) { _deleteCommand = new RelayCommand( param => Delete(), param => CanDelete ); } return _deleteCommand; } } public ICommand ClearCommand { get { if (_clearCommand == null) { _clearCommand = new RelayCommand( param => Clear(), param => CanClear ); } return _clearCommand; } } public ICommand MoveLastCommand { get { if (_moveLastCommand == null) { _moveLastCommand = new RelayCommand( param => MoveLast(), param => CanMove ); } return _moveLastCommand; } } public ICommand MoveFirstCommand { get { if (_moveFirstCommand == null) { _moveFirstCommand = new RelayCommand( param => MoveFirst(), param => CanMove ); } return _moveFirstCommand; } } public ICommand MovePrevCommand { get { if (_movePrevCommand == null) { _movePrevCommand = new RelayCommand( param => MovePrev(), param => CanMove ); } return _movePrevCommand; } } public ICommand MoveNextCommand { get { if (_moveNextCommand == null) { _moveNextCommand = new RelayCommand( param => MoveNext(), param => CanMove ); } return _moveNextCommand; } } private void PopulateProperties(DTOArticle article) { ArticleID = article.ArticleID.ToString(); Title = article.Title; Body = article.Body; } private void PopulateProperties(List<DTOArticle> articles, int idxx) { ArticleID = articles[idxx].ArticleID.ToString(); Title = articles[idxx].Title; Body = articles[idxx].Body; } private void Update() { if(_articles != null) { _articles[idx].Title = Title; _articles[idx].Body = Body; _articles[idx].IsUpdate = true; } base.OnPropertyChanged("DisplayName"); } private void Add() { if (_articles != null) { if (Title != string.Empty && Body != string.Empty && ArticleID == "Article not saved yet.") { var dto = new DTOArticle {ArticleID = -1, AuthorID = 1, Title = Title, Body = Body, IsUpdate = false}; _articles.Add(dto); idx = _articles.Count - 1; } } base.OnPropertyChanged("DisplayName"); } private void Save() { if (_articles != null) { var atleastonearticle = (from a in _articles.Where(a => a.IsUpdate || a.ArticleID == -1) select a).FirstOrDefault(); if (atleastonearticle != null) { _articles = mService.SaveArticles(_articles); PopulateProperties(_articles, idx); } } base.OnPropertyChanged("DisplayName"); } private void Delete() { if (_articles.Count > 0) { var article = _articles[idx]; mService.DeleteArticle(article); _articles.RemoveAt(idx); idx = 0; PopulateProperties(_articles, idx); } } private void MoveLast() { if (_articles != null) { idx = _articles.Count - 1; PopulateProperties(_articles, idx); } base.OnPropertyChanged("DisplayName"); } private void MovePrev() { if (_articles != null) { if (idx == 0) { PopulateProperties(_articles, idx); } else { idx -= 1; PopulateProperties(_articles, idx); } } base.OnPropertyChanged("DisplayName"); } private void MoveNext() { if (_articles != null) { if (idx == _articles.Count - 1) { PopulateProperties(_articles, idx); } else { idx += 1; PopulateProperties(_articles, idx); } } base.OnPropertyChanged("DisplayName"); } private void MoveFirst() { if (_articles != null) { idx = 0; PopulateProperties(_articles, idx); } base.OnPropertyChanged("DisplayName"); } private void Clear() { Title = ""; Body = ""; ArticleID = "Article not saved yet."; } bool CanUpdate { get { return true; } } bool CanAdd { get { return true; } } bool CanDelete { get { return true; } } bool CanSave { get { return true; } } bool CanMove { get { return true; } } bool CanClear { get { return true; } } } }


    Friday, December 25, 2015 11:18 AM
  • http://social.msdn.microsoft.com/Forums/en-US/home?forum=adodotnetentityframework

    You can try the above forum and see if someone can help you.

    Saturday, December 26, 2015 6:30 PM
  • Hello

    This question is related to WCF DataService. So I am asking here.

    Regarding above given sample it is sample showing CRUD operation using WCF Data Service . But that I know things.

    My issue was I created DataContext property (Extra property) at Entity level & Also write the code to ignore custom property in WritingEntity event. But here in this case before this event some error comes. So want to know the actual reason what is going on.

    What kind of issue occur If I do so. Is it possible or not.

    Can you please guide me in that direction please?

    Regards

    Vipul Langalia

    Monday, December 28, 2015 11:42 AM
  • If that related to WCF DataService, you should post that question to following forum.

    WCF DataService

    • Proposed as answer by DA924 Wednesday, December 30, 2015 11:12 AM
    Wednesday, December 30, 2015 9:06 AM