I using WPF for my project. I have a want to get total value from Entities Framework Database and show it on main window. It work but when I changed value on datasource from sub window, it don't work automatically. I want after changed data on sub window, the total on main window will change immediately.
#namespace KhoLeco.ViewModel
{
public class BaseViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
}
// MainWindow:
namespace KhoLeco.ViewModel
{
public class MainViewModel : BaseViewModel
{
private double _TienDauCon;
public double TienDauCon { get => _TienDauCon; set { _TienDauCon = value; OnPropertyChanged(); } }
public bool IsLoaded = false;
public MainViewModel()
{
LoadedWindowCommand = new RelayCommand<Window>((p) => { return true; }, (p) =>
{
IsLoaded = true;
if (p == null)
return;
p.Hide();
LoginWindow loginWindow = new LoginWindow();
loginWindow.ShowDialog();
if (loginWindow.DataContext == null)
return;
var loginVM = loginWindow.DataContext as LoginViewModel;
if (loginVM.IsLogin)
{
p.Show();
LoadTienDau();
}
else
{
p.Close();
}
}
);
public void LoadTienDau()
{
TienDauCon =((int)DataProvider.Ins.DB.ChiTietPhieuDau.Sum(p => p.PayInfo) - (double)DataProvider.Ins.DB.ChiTietPhieuDau.Sum(p => p.Amount));
}
}
}
// TextBlock on main window:
<TextBlock Text="{Binding TienDauCon,IsAsync=True, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged,StringFormat={}{0:#,#.00}}">
</TextBlock>
// sub window:
namespace KhoLeco.ViewModel
{
public class TienDauViewModel : BaseViewModel
{
private ObservableCollection<ChiTietPhieuDau> _List;
public ObservableCollection<ChiTietPhieuDau> List { get => _List; set
{ _List = value; OnPropertyChanged(); } }
private ObservableCollection<XeTai> _XeTai;
public ObservableCollection<XeTai> XeTai { get => _XeTai; set { _XeTai = value; OnPropertyChanged(); } }
private ObservableCollection<MatHangDau> _MatHangDau;
public ObservableCollection<MatHangDau> MatHangDau { get => _MatHangDau; set { _MatHangDau = value; OnPropertyChanged(); } }
private ChiTietPhieuDau _SelectedItem;
public ChiTietPhieuDau SelectedItem
{
get => _SelectedItem;
set
{
_SelectedItem = value;
OnPropertyChanged();
if (SelectedItem != null)
{
Id = SelectedItem.Id;
//DateSuply = SelectedItem.DateSuply;
SelectedXeTai = SelectedItem.XeTai;
SelectedMatHangDau = SelectedItem.MatHangDau;
Count = SelectedItem.Count;
Price = SelectedItem.Price;
Amount = SelectedItem.Amount;
DateBuy = SelectedItem.DateBuy;
CountLocate = SelectedItem.CountLocate;
MoreInfo = SelectedItem.MoreInfo;
PayInfo = SelectedItem.PayInfo;
}
}
}
private XeTai _SelectedXeTai;
public XeTai SelectedXeTai
{
get => _SelectedXeTai;
set
{
_SelectedXeTai = value;
OnPropertyChanged();
}
}
private MatHangDau _SelectedMatHangDau;
public MatHangDau SelectedMatHangDau
{
get => _SelectedMatHangDau;
set
{
_SelectedMatHangDau = value;
OnPropertyChanged();
}
}
private int _Id;
public int Id { get => _Id; set { _Id = value; OnPropertyChanged(); } }
private int _Count;
public int Count { get => _Count; set { _Count = value; OnPropertyChanged(); } }
private Nullable<double> _Price;
public Nullable<double> Price { get => _Price; set { _Price = value; OnPropertyChanged(); } }
private Nullable<double> _Amount;
public Nullable<double> Amount { get => _Amount; set { _Amount = value; OnPropertyChanged(); } }
private Nullable<DateTime> _DateBuy;
public Nullable<DateTime> DateBuy { get => _DateBuy; set { _DateBuy = value; OnPropertyChanged(); } }
private Nullable<DateTime> _DateSuply;
public Nullable<DateTime> DateSuply { get => _DateSuply; set { _DateSuply = value; OnPropertyChanged(); } }
private Nullable<double> _CountLocate;
public Nullable<double> CountLocate { get => _CountLocate; set { _CountLocate = value; OnPropertyChanged(); } }
private Nullable<int> _PayInfo;
public Nullable<int> PayInfo { get => _PayInfo; set { _PayInfo = value; OnPropertyChanged(); } }
private string _MoreInfo;
public string MoreInfo { get => _MoreInfo; set { _MoreInfo = value; OnPropertyChanged(); } }
public ICommand PhieuDauCommand { get; set; }
public ICommand EditCommand { get; set; }
public TienDauViewModel()
{
List = new ObservableCollection<ChiTietPhieuDau>(DataProvider.Ins.DB.ChiTietPhieuDau.OrderByDescending(x => x.Id));
XeTai = new ObservableCollection<XeTai>(DataProvider.Ins.DB.XeTai);
MatHangDau = new ObservableCollection<MatHangDau>(DataProvider.Ins.DB.MatHangDau);
PhieuDauCommand = new RelayCommand<object>((p) => { return true; }, (p) =>
{
PhieuDauWindow wd = new PhieuDauWindow();
wd.ShowDialog();
});
EditCommand = new RelayCommand<object>((p) =>
{
if (SelectedItem == null)
return false;
var displayList = DataProvider.Ins.DB.ChiTietPhieuDau.Where(x => x.Id == SelectedItem.Id);
if (displayList != null && displayList.Count() != 0)
return true;
return false;
}, (p) =>
{
var TienDau = DataProvider.Ins.DB.ChiTietPhieuDau.Where(x => x.Id == SelectedItem.Id).SingleOrDefault();
TienDau.Id = Id;
TienDau.IdTruck = SelectedXeTai.Id;
TienDau.IdObject = SelectedMatHangDau.Id;
TienDau.Count = Count;
TienDau.Price = Price;
TienDau.Amount = Count * Price;
TienDau.CountLocate = CountLocate;
TienDau.DateBuy = DateBuy;
TienDau.PayInfo = PayInfo;
TienDau.MoreInfo = MoreInfo;
DataProvider.Ins.DB.SaveChanges();
// May I call LoadTienDau() here?
});
}
}
}
Related
JsonConvert.SerializeObject is returning an empty object
I can serialize a generic object, and I can serialize this object in a different assembly. I've verified the properties are public and also explicitly marked with json tags. No exception is being thrown by Newtonsoft.Json. Relevant version Newtonsoft.Json 12.0.2, installed via nuget.
The test is failing because the expected call and actual call are different. The actual call (not pasted) is what I expect, but the Json serializes gives an empty object in the test.
logger.Verify(m => m.LogUsage(JsonConvert.SerializeObject(_svc), "AddService", string.Empty, false), Times.Once());
UPDATE: I tried adding the following test and it still is serializing to an empty object, despite _svc being defined correctly (I can tell by setting a breakpoint and inspecting it.)
[TestMethod]
public async Task TestUnableToSerialize()
{
string result = JsonConvert.SerializeObject(_svc);
Assert.AreEqual(string.Empty, result);
}
[TestClass]
public class ServiceDirectoryTests
{
private Service _defaultSvc;
private ServiceInfoResponse _defaultSvcInfo;
private Mock<ILogger> logger;
private ILogger _logger;
public Service _svc;
private ServiceInfoResponse _svcInfo;
private List<string> _serviceMonikers;
private string _serialized;
[TestInitialize()]
public void Initialize()
{
logger = new Mock<ILogger>();
_logger = logger.Object;
_defaultSvcInfo = new ServiceInfoResponse()
{
endpoint = "default endpoint",
environment_id = string.Empty,
id = "defaultId",
iso_a2_country_code = "UK",
moniker = "Account",
tenant_moniker = "default",
url_selection_scheme = UrlSelectionScheme.ServiceDefault
};
_defaultSvc = new Service(_defaultSvcInfo);
_svcInfo = new ServiceInfoResponse()
{
endpoint = "service endpoint",
environment_id = string.Empty,
id = "nonDefaultId",
iso_a2_country_code = "UK",
moniker = "Account",
tenant_moniker = "ztorstrick",
url_selection_scheme = UrlSelectionScheme.ServiceDefault
};
_svc = new Service(_svcInfo);
}
[TestMethod]
public async Task AddServiceDefaultReturned()
{
Mock<IServiceDirectory> mockClient = new Mock<IServiceDirectory>();
mockClient.Setup(x => x.CreateService(
It.IsAny<string>(),
It.IsAny<string>(),
It.IsAny<string>(),
It.IsAny<string>(),
It.IsAny<string>(),
It.IsAny<string>(),
It.IsAny<string>()
))
.ReturnsAsync(_defaultSvcInfo);
ServiceDirectory svc = new ServiceDirectory(mockClient.Object, _logger);
Service result = await svc.AddService(_svc, "");
Assert.AreEqual(_defaultSvc.Endpoint, result.Default);
Assert.AreEqual(result.Default, result.Endpoint);
Assert.AreEqual(_defaultSvc.EnvironmentId, result.EnvironmentId);
Assert.AreEqual(string.Empty, result.Id);
Assert.AreEqual(_defaultSvc.IsoA2CountryCode, result.IsoA2CountryCode);
Assert.AreEqual(_defaultSvc.Moniker, result.Moniker);
Assert.AreEqual(_defaultSvc.ServiceName, result.ServiceName);
Assert.AreEqual(_defaultSvc.TenantMoniker, result.TenantMoniker);
Assert.AreEqual("ServiceDefault", result.UrlSelectionScheme);
logger.Verify(m => m.LogUsage(JsonConvert.SerializeObject(_svc), "AddService", string.Empty, false), Times.Once());
}
}
public class Service : PropertyChangedBase
{
#region " Private Variables "
private string _default;
private string _endpoint;
private string _environmentId;
private string _id;
private bool _isSelected;
private string _isoA2CountryCode;
private string _moniker;
private string _serviceName;
private string _tenantMoniker;
private string _urlSelectionScheme;
private string _version;
#endregion
#region "Constructors"
public Service()
{
Id = string.Empty;
IsDirty = false;
IsSelected = false;
}
public Service(Service service)
{
if (service == null) { throw new ArgumentNullException(); }
Default = service.Default;
Endpoint = service.Endpoint;
EnvironmentId = service.EnvironmentId;
Id = service.Id;
IsDirty = service.IsDirty;
IsoA2CountryCode = service.IsoA2CountryCode;
IsSelected = service.IsSelected;
Moniker = service.Moniker;
ServiceName = service.ServiceName;
TenantMoniker = service.TenantMoniker;
UrlSelectionScheme = service.UrlSelectionScheme;
// DO NOT keep Ids for default services, to prevent accidental editing and deletion
if (string.IsNullOrWhiteSpace(service.TenantMoniker) ||
string.Equals(service.TenantMoniker, "default", StringComparison.CurrentCultureIgnoreCase))
{
Id = string.Empty;
}
}
public Service(ServiceInfoResponse response)
{
if (response == null) { throw new ArgumentNullException(); }
IsDirty = false;
Endpoint = response.endpoint;
EnvironmentId = response.environment_id;
Id = response.id;
IsoA2CountryCode = response.iso_a2_country_code;
IsSelected = false;
Moniker = response.moniker;
ServiceName = response.service_name;
TenantMoniker = response.tenant_moniker;
UrlSelectionScheme = response.url_selection_scheme.ToString();
// DO NOT keep Ids for default services, to prevent accidental editing and deletion
if(string.IsNullOrWhiteSpace(response.tenant_moniker) ||
string.Equals(response.tenant_moniker, "default", StringComparison.CurrentCultureIgnoreCase))
{
Id = string.Empty;
}
}
#endregion
#region "Properties"
[JsonIgnore]
public string Default
{
get { return _default; }
set
{
if (_default != value)
{
_default = value;
NotifyOfPropertyChange(() => Default);
}
}
}
[JsonProperty("endpoint")]
public string Endpoint
{
get { return _endpoint; }
set
{
if (_endpoint != value)
{
_endpoint = value;
NotifyOfPropertyChange(() => Endpoint);
}
}
}
[JsonProperty("environment_id")]
public string EnvironmentId
{
get { return _environmentId; }
set
{
if (_environmentId != value)
{
_environmentId = value;
NotifyOfPropertyChange(() => EnvironmentId);
}
}
}
[JsonProperty("id")]
public string Id
{
get { return _id; }
set
{
if (_id != value)
{
_id = value;
NotifyOfPropertyChange(() => Id);
NotifyOfPropertyChange(() => IsDefault);
}
}
}
[JsonIgnore]
public bool IsDefault
{
get
{
return string.IsNullOrWhiteSpace(Id);
}
}
[JsonIgnore]
public bool IsDirty { get; set; }
public bool IsSelected
{
get { return _isSelected; }
set
{
if (_isSelected != value)
{
_isSelected = value;
NotifyOfPropertyChange(() => IsSelected);
}
}
}
[JsonProperty("iso_a2_country_code")]
public string IsoA2CountryCode
{
get { return _isoA2CountryCode; }
set
{
if (_isoA2CountryCode != value)
{
_isoA2CountryCode = value;
NotifyOfPropertyChange(() => IsoA2CountryCode);
}
}
}
[JsonIgnore]
public bool MatchesDefault { get { return string.Equals(Endpoint, Default, StringComparison.CurrentCultureIgnoreCase); } }
[JsonProperty("moniker")]
public string Moniker
{
get { return _moniker; }
set
{
if (_moniker != value)
{
_moniker = value;
NotifyOfPropertyChange(() => Moniker);
}
}
}
[JsonProperty("service_name")]
public string ServiceName
{
get { return _serviceName; }
set
{
if (_serviceName != value)
{
_serviceName = value;
NotifyOfPropertyChange(() => ServiceName);
}
}
}
[JsonProperty("tenant_moniker")]
public string TenantMoniker
{
get { return _tenantMoniker; }
set
{
if (_tenantMoniker != value)
{
_tenantMoniker = value;
NotifyOfPropertyChange(() => TenantMoniker);
}
}
}
[JsonProperty("url_selection_scheme")]
public string UrlSelectionScheme
{
get { return _urlSelectionScheme; }
set
{
if (_urlSelectionScheme != value)
{
_urlSelectionScheme = value;
NotifyOfPropertyChange(() => UrlSelectionScheme);
}
}
}
[JsonProperty("version")]
public string Version
{
get { return _version; }
set
{
if (_version != value)
{
_version = value;
NotifyOfPropertyChange(() => Version);
}
}
}
#endregion
}
I had a NuGet reference to Newtonsoft.Json in my unit test project. I removed that, rebuilt, and now it works. The only thing I can think is there were different versions of Json floating around (this has happened to me before) and it was breaking something.
I found this topic to be a real struggle for a lot of people here and it therefore is actually covered pretty good! Nevertheless, none of the provided solutions seems to work for me.
As the title says, its about the problem that ObservableCollection doesnt fire when the value of the item changes, only if the Item itself gets removed, added or changed in some way.
I tried solutions with BindingList- even though a lot of people disadvice it - and it didnt work, solutions with extended ObservableCollections like it is explained here. None of it seems to work...which leaves the question whether the error is where i think it is or somewhere completely else!!
Alright heres my code:
BaseClasses:
public class ModelBase : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged([CallerMemberName] string propName = "")
{
if (this.PropertyChanged != null)
{
this.PropertyChanged(this, new PropertyChangedEventArgs(propName));
}
}
}
class TestSensor : ModelBase
{
private bool isOnline;
public bool IsOnline
{
get
{
return isOnline;
}
set
{
if (isOnline != value)
{
isOnline = value;
this.OnPropertyChanged();
}
}
}
private double sensorDatauStrain;
public double SensorDatauStrain
{
get { return sensorDatauStrain; }
set
{
if (sensorDatauStrain != value)
{
sensorDatauStrain = value;
this.OnPropertyChanged();
}
}
}
private double sensorDatakNewton;
public double SensorDatakNewton
{
get { return sensorDatakNewton; }
set
{
if (sensorDatakNewton != value)
{
sensorDatakNewton = value;
this.OnPropertyChanged();
}
}
}
private double sensorDataTon;
public double SensorDataTon
{
get { return sensorDataTon; }
set
{
if (sensorDataTon != value)
{
sensorDataTon = value;
this.OnPropertyChanged();
}
}
}
private double sensorDatausTon;
public double SensorDatausTon
{
get { return sensorDatausTon; }
set
{
if (sensorDatausTon != value)
{
sensorDatausTon = value;
this.OnPropertyChanged();
}
}
}
private string sensorName;
public string SensorName
{
get { return sensorName; }
set
{
if (sensorName != value)
{
sensorName = value;
this.OnPropertyChanged();
}
}
}
public TestSensor(string name, double ustrain,double kNewton, double ton, double uston)
{
this.SensorName = name;
this.SensorDatauStrain = ustrain;
this.SensorDatakNewton = kNewton;
this.SensorDataTon = ton;
this.SensorDatausTon = uston;
this.IsOnline = true;
}
}
Then i have a class containing these Sensors:
class Holm : ModelBase
{
public Holm(String Name, TestSensor sensor1, TestSensor sensor2)
{
Sensor1 = sensor1;
Sensor2 = sensor2;
this.Name = Name;
}
private string name;
public string Name
{
get
{
return name;
}
set
{
if (name != value)
{
name = value;
this.OnPropertyChanged();
}
}
}
private TestSensor sensor1;
public TestSensor Sensor1
{
get
{
return sensor1;
}
set
{
if (sensor1 != value)
{
sensor1 = value;
this.OnPropertyChanged();
}
}
}
private TestSensor sensor2;
public TestSensor Sensor2
{
get
{
return sensor2;
}
set
{
if (sensor2 != value)
{
sensor2 = value;
this.OnPropertyChanged();
}
}
}
public bool IsOnline
{
get
{
if (!Sensor1.IsOnline || !Sensor2.IsOnline)
{
return false;
}
else
{
return true;
}
}
}
}
And finally the ViewModel that contains my failing ObservableCollection - excluding some things that are not relevant:
class MainViewViewModel : ModelBase
{
public ItemsChangeObservableCollection<Holm> HolmList { get;set;}
public MainViewViewModel()
{
Sensor11 = new TestSensor("Sensor 1.1", 0, 0, 0, 0);
Sensor12 = new TestSensor("Sensor 1.2", 0, 0, 0, 0);
Sensor21 = new TestSensor("Sensor 2.1", 0, 0, 0, 0);
Sensor22 = new TestSensor("Sensor 2.2", 0, 0, 0, 0);
Sensor31 = new TestSensor("Sensor 3.1", 0, 0, 0, 0);
Sensor32 = new TestSensor("Sensor 3.2", 0, 0, 0, 0);
Sensor41 = new TestSensor("Sensor 4.1", 0, 0, 0, 0);
Sensor42 = new TestSensor("Sensor 4.2", 0, 0, 0, 0);
Holm1 = new Holm("Holm 1", Sensor11, Sensor12);
Holm2 = new Holm("Holm 2", Sensor21, Sensor22);
Holm3 = new Holm("Holm 3", Sensor31, Sensor32);
Holm4 = new Holm("Holm 4", Sensor41, Sensor42);
HolmList = new ItemsChangeObservableCollection<Holm>();
HolmList.Add(Holm1);
HolmList.Add(Holm2);
HolmList.Add(Holm3);
HolmList.Add(Holm4);
}
private TestSensor sensor11;
public TestSensor Sensor11
{
get { return sensor11; }
set
{
if (sensor11 != value)
{
sensor11 = value;
this.OnPropertyChanged();
this.OnPropertyChanged("Holm1");
this.OnPropertyChanged("HolmList");
}
}
}
private TestSensor sensor12;
public TestSensor Sensor12
{
get { return sensor12; }
set
{
if (sensor12 != value)
{
sensor12 = value;
this.OnPropertyChanged();
this.OnPropertyChanged("Holm1");
this.OnPropertyChanged("HolmList");
}
}
}
private TestSensor sensor21;
public TestSensor Sensor21
{
get { return sensor21; }
set
{
if (sensor21 != value)
{
sensor21 = value;
this.OnPropertyChanged();
}
}
}
private TestSensor sensor22;
public TestSensor Sensor22
{
get { return sensor22; }
set
{
if (sensor22 != value)
{
sensor22 = value;
this.OnPropertyChanged();
}
}
}
private TestSensor sensor31;
public TestSensor Sensor31
{
get { return sensor31; }
set
{
if (sensor31 != value)
{
sensor31 = value;
this.OnPropertyChanged();
}
}
}
private TestSensor sensor32;
public TestSensor Sensor32
{
get { return sensor32; }
set
{
if (sensor32 != value)
{
sensor32 = value;
this.OnPropertyChanged();
}
}
}
private TestSensor sensor41;
public TestSensor Sensor41
{
get { return sensor41; }
set
{
if (sensor41 != value)
{
sensor41 = value;
this.OnPropertyChanged();
}
}
}
private TestSensor sensor42;
public TestSensor Sensor42
{
get { return sensor42; }
set
{
if (sensor42 != value)
{
sensor42 = value;
this.OnPropertyChanged();
}
}
}
private Holm holm1;
public Holm Holm1
{
get
{
return holm1;
}
set
{
if (holm1 != value)
{
holm1 = value;
this.OnPropertyChanged();
this.OnPropertyChanged("HolmList");
}
}
}
private Holm holm2;
public Holm Holm2
{
get
{
return holm2;
}
set
{
if (holm2 != value)
{
holm2 = value;
this.OnPropertyChanged();
}
}
}
private Holm holm3;
public Holm Holm3
{
get
{
return holm3;
}
set
{
if (holm3 != value)
{
holm3 = value;
this.OnPropertyChanged();
}
}
}
private Holm holm4;
public Holm Holm4
{
get
{
return holm4;
}
set
{
if (holm4 != value)
{
holm4 = value;
this.OnPropertyChanged();
}
}
}
}
The Xaml isnt really important and is not yet finished. I have solved it so far with this code:
<CheckBox Content="Sensor1.1" IsChecked="{Binding HolmList[0].Sensor1.IsOnline}"/>
<TextBlock Text="{Binding HolmList[0].Sensor1.IsOnline, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}"/>
<CheckBox Content="Sensor1.2" IsChecked="{Binding HolmList[0].Sensor2.IsOnline}"/>
<TextBlock Text="{Binding HolmList[0].Sensor2.IsOnline, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}"/>
<TextBlock Text="{Binding HolmList[0].IsOnline, UpdateSourceTrigger=PropertyChanged}" />
All i want is the Holms IsOnline-Property to change to false as soon as one of the Sensors IsOnline-Property changes to false...but it just wouldnt!
In know this is a lot of code, but im actually not sure where the error is located.
Also: It seems to me that my classed have redundant calls to OnPropertyChange()...but im not sure bout it.
Im really thankful for all kind of help on this!!!
Your TextBlock that bound to HolmList[0].IsOnline didn't update because IsOnline on Holm didn't notify that its value changed.
You can listen to TestSensor's PropertyChanged event in TestSensor and notify IsOnline property change when one of TestSensor's IsOnline property change.
class Holm : ModelBase
{
public Holm(String Name, TestSensor sensor1, TestSensor sensor2)
{
Sensor1 = sensor1;
Sensor2 = sensor2;
this.Name = Name;
Sensor1.PropertyChanged += OnSensorOnlineChanged;
Sensor2.PropertyChanged += OnSensorOnlineChanged;
}
private void OnSensorOnlineChanged(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == "IsOnline")
{
OnPropertyChanged(nameof(IsOnline));
}
}
}
The nameof keyword
you mean something like this?
public class EnhancedObservableCollection<T> : ObservableCollection<T>
where T : INotifyPropertyChanged
{
public EnhancedObservableCollection(bool isCollectionChangedOnChildChange)
{
IsCollectionChangedOnChildChange = isCollectionChangedOnChildChange;
}
public EnhancedObservableCollection(List<T> list, bool isCollectionChangedOnChildChange) : base(list)
{
IsCollectionChangedOnChildChange = isCollectionChangedOnChildChange;
}
public EnhancedObservableCollection(IEnumerable<T> collection, bool isCollectionChangedOnChildChange) : base(collection)
{
IsCollectionChangedOnChildChange = isCollectionChangedOnChildChange;
}
public bool IsCollectionChangedOnChildChange { get; set; }
public event EventHandler<string> ChildChanged;
protected override void RemoveItem(int index)
{
var item = Items[index];
item.PropertyChanged -= ItemOnPropertyChanged;
base.RemoveItem(index);
}
private void ItemOnPropertyChanged(object sender, PropertyChangedEventArgs propertyChangedEventArgs)
{
var handler = ChildChanged;
if (handler != null)
{
handler(this, propertyChangedEventArgs.PropertyName);
}
if (IsCollectionChangedOnChildChange)
{
OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Replace));
}
}
protected override void InsertItem(int index, T item)
{
base.InsertItem(index, item);
item.PropertyChanged += ItemOnPropertyChanged;
}
}
i know that this question have asked many times but i havent find any answer that can help me
the problem is
the-objectcontext-instance-has-been-disposed-and-can-no-longer-be-used-for-operations-that-require-a-connection
after i declare copy of entity object that have linked to other entity with 1 to many relation
this is the class
using System;
using System.Linq;
using School.Component;
using System.Windows.Input;
using DataAccess;
using System.Collections.ObjectModel;
using DataAccess.Repository;
using Microsoft.Practices.Prism.Commands;
using System.Collections.Generic;
namespace School.WpfApp.ViewModels
{
public class LevelsPerYearNewVM : ViewModelBase
{
SchAvaiLevelsPerYear _CurrentLevelsPerYear;
SchAvaiLevelsPerYear _old;
private bool _isnew = false;
bool _IsEnabled = false;
StudyYearRepository _Repository = new StudyYearRepository();
SchoolSettingRepository _SRepository = new SchoolSettingRepository();
ObservableCollection<StageLevel> _AllStageLevel;
StageLevel _SelectrdStageLevel;
ObservableCollection<SchAvaiLevelsPerYear> _allSchAvaiLevelsPerYear;
ObservableCollection<CoursesLevelsPerStYear> _AllCoursesLevelsPerStYear;
private string errorMasseg;
public LevelsPerYearNewVM(SchAvaiLevelsPerYear f, ObservableCollection<SchAvaiLevelsPerYear> _list)
: base()
{
_old = (f);
CurrentLevelsPerYear = new SchAvaiLevelsPerYear()
{
Avalible = f.Avalible,
CoursCount = f.CoursCount,
YearID = f.YearID,
ID = f.ID,
SchoolID = f.SchoolID,
UserID = f.UserID,
StageLevelID = f.StageLevelID,
};
InitVars();
CreateCommands();
ErrorMasseg = "";
if (_CurrentLevelsPerYear.ID > 0)
{
this.Title = "تعديل بيانات المستوى الدراسي";
}
else
{ this.Title = "اضافة مستوى دراسي"; IsEnabled = true; _isnew = true; }
_allSchAvaiLevelsPerYear = _list;
}
protected override async void InitVars()
{
AllStageLevel = await _SRepository.GetAllStageLevelsIncludeCourses();
if(!isnew)
AllCoursesLevelsPerStYear = await _SRepository.GetAllAllCoursesLevelsPerStYearBySchAvaiLevelsPerYearID( _CurrentLevelsPerYear.ID);
}
protected override void CreateCommands()
{
SaveCommand = new RelayCommand(o =>
{
Save();
}
, o => Valdite());
CanselCommand = new DelegateCommand(() =>
{
if (Closed != null)
{
_CurrentLevelsPerYear = null;
Closed(_CurrentLevelsPerYear);
}
}
, () => true);
}
private void Save()
{
SchAvaiLevelsPerYear a = null;
string masseg = "";
if (Valdite())
{
a = _allSchAvaiLevelsPerYear.FirstOrDefault(i => i.ID != CurrentLevelsPerYear.ID && i.StageLevelID == _CurrentLevelsPerYear.StageLevelID);
if (a == null)
{
_CurrentLevelsPerYear.CoursCount = _AllCoursesLevelsPerStYear.Where(cc=>cc.Avalible).Count();
_CurrentLevelsPerYear.UserID = Session.SessionData.CurrentUser.UserID;
_CurrentLevelsPerYear.ID = _Repository.SaveSchAvaiLevelsPerYear(_CurrentLevelsPerYear);
CoursesLevelsPerStYear v;
foreach (CoursesLevelsPerStYear c in _AllCoursesLevelsPerStYear)
{
if (_isnew)
c.SALByYearID = _CurrentLevelsPerYear.ID;
c.UserID = Session.SessionData.CurrentUser.UserID;
v = (CoursesLevelsPerStYear)MyDataAccessTools.Clone<CoursesLevelsPerStYear>(c);
c.ID= _Repository.SaveCoursesLevelsPerStYearDirctliy(v);
}
///// the error massage aaper her when i use break point to know what are the changes that have been done
_CurrentLevelsPerYear.CoursesLevelsPerStYears = _AllCoursesLevelsPerStYear
//////
/////
}
else
masseg = "يوجد مستوى دراسي مماثل";
}
if (string.IsNullOrWhiteSpace(masseg))
Closed(a);
else
ErrorMasseg = masseg;
}
private bool Valdite()
{
bool result = false;
if (_CurrentLevelsPerYear != null && _CurrentLevelsPerYear.StageLevelID>0 )
result = true;
return result;
}
public override void Reset()
{
}
public SchAvaiLevelsPerYear CurrentLevelsPerYear
{
get { return _CurrentLevelsPerYear; }
set
{
if (_CurrentLevelsPerYear != value)
{
_CurrentLevelsPerYear = value;
NotifyPropertyChanged("CurrentLevelsPerYear");
}
}
}
public ObservableCollection<StageLevel> AllStageLevel
{
get { return _AllStageLevel; }
set
{
if (_AllStageLevel != value)
{
_AllStageLevel = value;
NotifyPropertyChanged("AllStageLevel");
}
}
}
public StageLevel SelectrdStageLevel
{
get { return _SelectrdStageLevel; }
set
{
if (_SelectrdStageLevel != value)
{
_SelectrdStageLevel = value;
NotifyPropertyChanged("SelectrdStageLevel");
if (_isnew)
{
ObservableCollection<CoursesLevelsPerStYear> allcby = new ObservableCollection<CoursesLevelsPerStYear>();
CoursesLevelsPerStYear cby;
foreach (CoursesByLevel cbl in _SelectrdStageLevel.CoursesByLevels)
{
cby = new CoursesLevelsPerStYear() {StartDate = Session.SessionData.CurrentYear.StartDate, Avalible =true
, CoursByLevelID = cbl.ID , CoursesByLevel= cbl, UserID = Session.SessionData.CurrentUser.UserID,
MaxLecturePerWeak = cbl.MaxLecturePerWeak,MinLecturePerWeak = cbl.MinLecturePerWeak,
SchAvaiLevelsPerYear = _CurrentLevelsPerYear
};
allcby.Add(cby);
}
AllCoursesLevelsPerStYear = allcby;
}
}
}
}
public ObservableCollection<CoursesLevelsPerStYear> AllCoursesLevelsPerStYear
{
get { return _AllCoursesLevelsPerStYear; }
set
{
if (_AllCoursesLevelsPerStYear != value)
{
_AllCoursesLevelsPerStYear = value;
NotifyPropertyChanged("AllCoursesLevelsPerStYear");
}
}
}
public bool IsEnabled
{
get { return _IsEnabled; }
set
{
if (_IsEnabled != value)
{
_IsEnabled = value;
NotifyPropertyChanged("IsEnabled");
}
}
}
public string ErrorMasseg
{
get { return errorMasseg; }
private set
{
if (value != errorMasseg)
{
errorMasseg = value;
NotifyPropertyChanged("ErrorMasseg");
}
}
}
public event Action<SchAvaiLevelsPerYear> Closed;
public ICommand SaveCommand
{
private set;
get;
}
public DelegateCommand CanselCommand
{
private set;
get;
}
}
}
this the entity
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated from a template.
//
// Manual changes to this file may cause unexpected behavior in your application.
// Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace DataAccess
{
using System;
using System.Collections.ObjectModel;
public partial class SchAvaiLevelsPerYear : BaseModel
{
public SchAvaiLevelsPerYear()
{
this.CoursesLevelsPerStYears = new ObservableCollection<CoursesLevelsPerStYear>();
this.StduyYearLevelFrogs = new ObservableCollection<StduyYearLevelFrog>();
}
private int _iD;
public int ID
{
get { return _iD; }
set { SetProperty(ref _iD, value); }
}
private int _yearID;
public int YearID
{
get { return _yearID; }
set { SetProperty(ref _yearID, value); }
}
private int _stageLevelID;
public int StageLevelID
{
get { return _stageLevelID; }
set { SetProperty(ref _stageLevelID, value); }
}
private int _schoolID;
public int SchoolID
{
get { return _schoolID; }
set { SetProperty(ref _schoolID, value); }
}
private bool _avalible;
public bool Avalible
{
get { return _avalible; }
set { SetProperty(ref _avalible, value); }
}
private int _coursCount;
public int CoursCount
{
get { return _coursCount; }
set { SetProperty(ref _coursCount, value); }
}
private byte[] _timestamp;
public byte[] Timestamp
{
get { return _timestamp; }
set { SetProperty(ref _timestamp, value); }
}
private int _userID;
public int UserID
{
get { return _userID; }
set { SetProperty(ref _userID, value); }
}
public virtual Branch Branch { get; set; }
public virtual ObservableCollection<CoursesLevelsPerStYear> CoursesLevelsPerStYears { get; set; }
public virtual StageLevel StageLevel { get; set; }
public virtual StudyYear StudyYear { get; set; }
public virtual ObservableCollection<StduyYearLevelFrog> StduyYearLevelFrogs { get; set; }
}
}
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated from a template.
//
// Manual changes to this file may cause unexpected behavior in your application.
// Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace DataAccess
{
using System;
using System.Collections.ObjectModel;
public partial class CoursesLevelsPerStYear : BaseModel
{
public CoursesLevelsPerStYear()
{
this.CourseGroups = new ObservableCollection<CourseGroup>();
this.Teachers = new ObservableCollection<Teacher>();
}
private int _iD;
public int ID
{
get { return _iD; }
set { SetProperty(ref _iD, value); }
}
private int _coursByLevelID;
public int CoursByLevelID
{
get { return _coursByLevelID; }
set { SetProperty(ref _coursByLevelID, value); }
}
private int _sALByYearID;
public int SALByYearID
{
get { return _sALByYearID; }
set { SetProperty(ref _sALByYearID, value); }
}
private int _maxLecturePerWeak;
public int MaxLecturePerWeak
{
get { return _maxLecturePerWeak; }
set { SetProperty(ref _maxLecturePerWeak, value); }
}
private int _minLecturePerWeak;
public int MinLecturePerWeak
{
get { return _minLecturePerWeak; }
set { SetProperty(ref _minLecturePerWeak, value); }
}
private bool _haveGroup;
public bool HaveGroup
{
get { return _haveGroup; }
set { SetProperty(ref _haveGroup, value); }
}
private bool _avalible;
public bool Avalible
{
get { return _avalible; }
set { SetProperty(ref _avalible, value); }
}
private Nullable<int> _holeID;
public Nullable<int> HoleID
{
get { return _holeID; }
set { SetProperty(ref _holeID, value); }
}
private bool _hasHole;
public bool HasHole
{
get { return _hasHole; }
set { SetProperty(ref _hasHole, value); }
}
private System.DateTime _startDate;
public System.DateTime StartDate
{
get { return _startDate; }
set { SetProperty(ref _startDate, value); }
}
private Nullable<System.DateTime> _stopDate;
public Nullable<System.DateTime> StopDate
{
get { return _stopDate; }
set { SetProperty(ref _stopDate, value); }
}
private byte[] _timestamp;
public byte[] Timestamp
{
get { return _timestamp; }
set { SetProperty(ref _timestamp, value); }
}
private int _userID;
public int UserID
{
get { return _userID; }
set { SetProperty(ref _userID, value); }
}
public virtual ObservableCollection<CourseGroup> CourseGroups { get; set; }
public virtual CoursesByLevel CoursesByLevel { get; set; }
public virtual Hole Hole { get; set; }
public virtual SchAvaiLevelsPerYear SchAvaiLevelsPerYear { get; set; }
public virtual ObservableCollection<Teacher> Teachers { get; set; }
}
}
namespace DataAccess
{
partial class CoursesLevelsPerStYear : BaseModel
{
private bool _CanEdit;
public bool CanEdit
{
get { return _CanEdit; }
set
{
SetProperty(ref _CanEdit, value);
}
}
private bool _EditMode;
public bool EditMode
{
get { return _EditMode; }
set
{
SetProperty(ref _EditMode, value);
}
}
string _EditButtonVisibility = "";
public string EditButtonVisibility
{
get
{
return _EditButtonVisibility;
}
set { SetProperty(ref _EditButtonVisibility, value); }
}
}
}
this only relation that Have problem like this . yes i have forget to mention that i change the DBContext of the entity framework using this and this
and i am using entity framework 6.2
excuse my english i am not a good english writer .
This is my code that I am trying to bind a datagrid to:
var query = (from s in entity.Sources
where s.CorporationId == corporationId
select new SourceItem
{
CorporationId = s.CorporationId,
Description=s.Description,
IsActive = s.IsActive,
Name=s.Name,
SourceId=s.SourceId,
TokenId=s.TokenId
});
var x = new ObservableCollection<Source>(query);
And this is my SourceItetm class:
private void SourceDataGrid_AddingNewItem(object sender, System.Windows.Controls.AddingNewItemEventArgs e)
{
var sources = new Source();
sources.CorporationId = _corporationId;
sources.Description = string.Empty;
sources.IsActive = true;
sources.Name = string.Empty;
sources.SourceId = Guid.NewGuid();
sources.TokenId = Guid.NewGuid();
e.NewItem = sources;
}
public class SourceItem
{
private Guid _corporationId1;
private string _description;
private bool _isActive;
private string _name;
private Guid _sourceId;
private Guid _tokenId;
public Guid CorporationId
{
set
{
_corporationId1 = value;
onPropertyChanged(this, "CorporationId");
}
get { return _corporationId1; }
}
public string Description
{
set
{
_description = value;
onPropertyChanged(this, "Description");
}
get { return _description; }
}
public bool IsActive
{
set
{
_isActive = value;
onPropertyChanged(this, "IsActive");
}
get { return _isActive; }
}
public string Name
{
set
{
_name = value;
onPropertyChanged(this, "NAme");
}
get { return _name; }
}
public Guid SourceId
{
set
{
_sourceId = value;
onPropertyChanged(this, "SourceId");
}
get { return _sourceId; }
}
public Guid TokenId
{
set
{
_tokenId = value;
onPropertyChanged(this, "TokenId");
}
get { return _tokenId; }
}
// Declare the PropertyChanged event
public event PropertyChangedEventHandler PropertyChanged;
// OnPropertyChanged will raise the PropertyChanged event passing the
// source property that is being updated.
private void onPropertyChanged(object sender, string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(sender, new PropertyChangedEventArgs(propertyName));
}
}
}
}
I'm having problems getting the binding right. This line in particular:
var x = new ObservableCollection<Source>(query);
It is telling me that it cannot resolve constructor.
Am I doing the binding right?
The type you select is SourceItem therefore you should use:
new ObservableCollection<SourceItem>(query.ToList());
I have a view in my database. The entity for the view has a primary key mark with IsPrimaryKey=true.
When i run db.MyEntity.DeleteAllOnSubmit(items);
I see the entity is marked for deletion however, no SQL is generated when db.SubmitChanges(); is called.
I use SQL profiler and no sql is generated or executed for the deletion.
Any suggestions??
DBML entry for the view:
[global::System.Data.Linq.Mapping.TableAttribute(Name="MyView")]
public partial class Entity4ShowEntity1 : INotifyPropertyChanging, INotifyPropertyChanged
{
private static PropertyChangingEventArgs emptyChangingEventArgs = new PropertyChangingEventArgs(String.Empty);
private string _Unid;
private string _Col1;
private string _Col2;
private string _Col3;
private string _Col4;
private System.Nullable<System.DateTime> _LastUpdate;
private string _Col5;
private string _Col6;
private System.Nullable<bool> _IsActive;
private System.Nullable<bool> _IsDirty;
private EntityRef<Entity1> _Entity1;
private EntityRef<Entity2> _Entity2;
private EntityRef<Entity3> _Entity3;
private EntityRef<Entity4> _Entity4;
#region Extensibility Method Definitions
partial void OnLoaded();
partial void OnValidate(System.Data.Linq.ChangeAction action);
partial void OnCreated();
partial void OnUnidChanging(string value);
partial void OnUnidChanged();
partial void OnEntity4UnidChanging(string value);
partial void OnEntity4UnidChanged();
partial void OnEntity3UnidChanging(string value);
partial void OnEntity3UnidChanged();
partial void OnEntity2UnidChanging(string value);
partial void OnEntity2UnidChanged();
partial void OnEntity1UnidChanging(string value);
partial void OnEntity1UnidChanged();
partial void OnLastUpdateChanging(System.Nullable<System.DateTime> value);
partial void OnLastUpdateChanged();
partial void OnUserUnidChanging(string value);
partial void OnUserUnidChanged();
partial void OnRemarksChanging(string value);
partial void OnRemarksChanged();
partial void OnIsActiveChanging(System.Nullable<bool> value);
partial void OnIsActiveChanged();
partial void OnIsDirtyChanging(System.Nullable<bool> value);
partial void OnIsDirtyChanged();
#endregion
public Entity4ShowEntity1()
{
this._Entity1 = default(EntityRef<Entity1>);
this._Entity2 = default(EntityRef<Entity2>);
this._Entity3 = default(EntityRef<Entity3>);
this._Entity4 = default(EntityRef<Entity4>);
OnCreated();
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_Unid", DbType="NVarChar(55) NOT NULL", CanBeNull=false, IsPrimaryKey=true)]
public string Unid
{
get
{
return this._Unid;
}
set
{
if ((this._Unid != value))
{
this.OnUnidChanging(value);
this.SendPropertyChanging();
this._Unid = value;
this.SendPropertyChanged("Unid");
this.OnUnidChanged();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_Col1", DbType="NVarChar(55) NOT NULL", CanBeNull=false, UpdateCheck=UpdateCheck.Never)]
public string Entity4Unid
{
get
{
return this._Col1;
}
set
{
if ((this._Col1 != value))
{
if (this._Entity4.HasLoadedOrAssignedValue)
{
throw new System.Data.Linq.ForeignKeyReferenceAlreadyHasValueException();
}
this.OnEntity4UnidChanging(value);
this.SendPropertyChanging();
this._Col1 = value;
this.SendPropertyChanged("Entity4Unid");
this.OnEntity4UnidChanged();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_Col2", DbType="NVarChar(55) NOT NULL", CanBeNull=false, UpdateCheck=UpdateCheck.Never)]
public string Entity3Unid
{
get
{
return this._Col2;
}
set
{
if ((this._Col2 != value))
{
if (this._Entity3.HasLoadedOrAssignedValue)
{
throw new System.Data.Linq.ForeignKeyReferenceAlreadyHasValueException();
}
this.OnEntity3UnidChanging(value);
this.SendPropertyChanging();
this._Col2 = value;
this.SendPropertyChanged("Entity3Unid");
this.OnEntity3UnidChanged();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_Col3", DbType="NVarChar(55) NOT NULL", CanBeNull=false, UpdateCheck=UpdateCheck.Never)]
public string Entity2Unid
{
get
{
return this._Col3;
}
set
{
if ((this._Col3 != value))
{
if (this._Entity2.HasLoadedOrAssignedValue)
{
throw new System.Data.Linq.ForeignKeyReferenceAlreadyHasValueException();
}
this.OnEntity2UnidChanging(value);
this.SendPropertyChanging();
this._Col3 = value;
this.SendPropertyChanged("Entity2Unid");
this.OnEntity2UnidChanged();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_Col4", DbType="NVarChar(55)", UpdateCheck=UpdateCheck.Never)]
public string Entity1Unid
{
get
{
return this._Col4;
}
set
{
if ((this._Col4 != value))
{
if (this._Entity1.HasLoadedOrAssignedValue)
{
throw new System.Data.Linq.ForeignKeyReferenceAlreadyHasValueException();
}
this.OnEntity1UnidChanging(value);
this.SendPropertyChanging();
this._Col4 = value;
this.SendPropertyChanged("Entity1Unid");
this.OnEntity1UnidChanged();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_LastUpdate", DbType="DateTime", UpdateCheck=UpdateCheck.Never)]
public System.Nullable<System.DateTime> LastUpdate
{
get
{
return this._LastUpdate;
}
set
{
if ((this._LastUpdate != value))
{
this.OnLastUpdateChanging(value);
this.SendPropertyChanging();
this._LastUpdate = value;
this.SendPropertyChanged("LastUpdate");
this.OnLastUpdateChanged();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_Col5", DbType="NVarChar(55)", UpdateCheck=UpdateCheck.Never)]
public string UserUnid
{
get
{
return this._Col5;
}
set
{
if ((this._Col5 != value))
{
this.OnUserUnidChanging(value);
this.SendPropertyChanging();
this._Col5 = value;
this.SendPropertyChanged("UserUnid");
this.OnUserUnidChanged();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_Col6", DbType="NVarChar(255)", UpdateCheck=UpdateCheck.Never)]
public string Remarks
{
get
{
return this._Col6;
}
set
{
if ((this._Col6 != value))
{
this.OnRemarksChanging(value);
this.SendPropertyChanging();
this._Col6 = value;
this.SendPropertyChanged("Remarks");
this.OnRemarksChanged();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_IsActive", DbType="Bit", UpdateCheck=UpdateCheck.Never)]
public System.Nullable<bool> IsActive
{
get
{
return this._IsActive;
}
set
{
if ((this._IsActive != value))
{
this.OnIsActiveChanging(value);
this.SendPropertyChanging();
this._IsActive = value;
this.SendPropertyChanged("IsActive");
this.OnIsActiveChanged();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_IsDirty", DbType="Bit", UpdateCheck=UpdateCheck.Never)]
public System.Nullable<bool> IsDirty
{
get
{
return this._IsDirty;
}
set
{
if ((this._IsDirty != value))
{
this.OnIsDirtyChanging(value);
this.SendPropertyChanging();
this._IsDirty = value;
this.SendPropertyChanged("IsDirty");
this.OnIsDirtyChanged();
}
}
}
[global::System.Data.Linq.Mapping.AssociationAttribute(Name="Entity1_Entity4ShowEntity1", Storage="_Entity1", ThisKey="Entity1Unid", OtherKey="Unid", IsForeignKey=true)]
public Entity1 Entity1
{
get
{
return this._Entity1.Entity;
}
set
{
Entity1 previousValue = this._Entity1.Entity;
if (((previousValue != value)
|| (this._Entity1.HasLoadedOrAssignedValue == false)))
{
this.SendPropertyChanging();
if ((previousValue != null))
{
this._Entity1.Entity = null;
previousValue.MyView.Remove(this);
}
this._Entity1.Entity = value;
if ((value != null))
{
value.MyView.Add(this);
this._Col4 = value.Unid;
}
else
{
this._Col4 = default(string);
}
this.SendPropertyChanged("Entity1");
}
}
}
[global::System.Data.Linq.Mapping.AssociationAttribute(Name="Entity2_Entity4ShowEntity1", Storage="_Entity2", ThisKey="Entity2Unid", OtherKey="Unid", IsForeignKey=true)]
public Entity2 Entity2
{
get
{
return this._Entity2.Entity;
}
set
{
Entity2 previousValue = this._Entity2.Entity;
if (((previousValue != value)
|| (this._Entity2.HasLoadedOrAssignedValue == false)))
{
this.SendPropertyChanging();
if ((previousValue != null))
{
this._Entity2.Entity = null;
previousValue.MyView.Remove(this);
}
this._Entity2.Entity = value;
if ((value != null))
{
value.MyView.Add(this);
this._Col3 = value.Unid;
}
else
{
this._Col3 = default(string);
}
this.SendPropertyChanged("Entity2");
}
}
}
[global::System.Data.Linq.Mapping.AssociationAttribute(Name="Entity3_Entity4ShowEntity1", Storage="_Entity3", ThisKey="Entity3Unid", OtherKey="Unid", IsForeignKey=true)]
public Entity3 Entity3
{
get
{
return this._Entity3.Entity;
}
set
{
Entity3 previousValue = this._Entity3.Entity;
if (((previousValue != value)
|| (this._Entity3.HasLoadedOrAssignedValue == false)))
{
this.SendPropertyChanging();
if ((previousValue != null))
{
this._Entity3.Entity = null;
previousValue.MyView.Remove(this);
}
this._Entity3.Entity = value;
if ((value != null))
{
value.MyView.Add(this);
this._Col2 = value.Unid;
}
else
{
this._Col2 = default(string);
}
this.SendPropertyChanged("Entity3");
}
}
}
[global::System.Data.Linq.Mapping.AssociationAttribute(Name="Entity4_Entity4ShowEntity1", Storage="_Entity4", ThisKey="Entity4Unid", OtherKey="Unid", IsForeignKey=true)]
public Entity4 Entity4
{
get
{
return this._Entity4.Entity;
}
set
{
Entity4 previousValue = this._Entity4.Entity;
if (((previousValue != value)
|| (this._Entity4.HasLoadedOrAssignedValue == false)))
{
this.SendPropertyChanging();
if ((previousValue != null))
{
this._Entity4.Entity = null;
previousValue.MyView.Remove(this);
}
this._Entity4.Entity = value;
if ((value != null))
{
value.MyView.Add(this);
this._Col1 = value.Unid;
}
else
{
this._Col1 = default(string);
}
this.SendPropertyChanged("Entity4");
}
}
}
public event PropertyChangingEventHandler PropertyChanging;
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void SendPropertyChanging()
{
if ((this.PropertyChanging != null))
{
this.PropertyChanging(this, emptyChangingEventArgs);
}
}
protected virtual void SendPropertyChanged(String propertyName)
{
if ((this.PropertyChanged != null))
{
this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
Make sure that db.ObjectTrackingEnabled = true;. By default it should be set to true, so you would have manually changed it to false. This is a good performance boost for when you want a read only (SELECT) mode for your DataContext. But you need to perform DELETE commands, so it needs to be true.