I'm a complete C# novice, please excuse my ignorance.
I'm trying to parse string values into a view-model. I'm having difficulty converting the database DateTime and Boolean values into strings as part of the LineOne, LineTwo and LineThree properties. How do I do this?
private void mapChecks()
{
bool FoundResult = false;
// Check if object is loaded
if (Items.Count == 0)
{
//Add everything
foreach (xtn_UnresolvedCheck check in MyChecks)
{
Items.Add(new ItemViewModel
{
LineOne = check.ClientName,
LineTwo = check.NSMDateTime,
LineThree = check.HaveRead,
MyappId = check.MonitoringID
}
);
}
}
ItemViewModel:
namespace App
{
public class ItemViewModel : INotifyPropertyChanged
{
private int _myappId;
public int MyappId
{
get
{
return _myappId;
}
set
{
if (value != _myappId)
{
_myappId = value;
NotifyPropertyChanged("MyappId");
}
}
}
private bool _isFavorite;
public bool IsFavorite
{
get
{
return _isFavorite;
}
set
{
if (value != _isFavorite)
{
_isFavorite = value;
NotifyPropertyChanged("IsFavorite");
}
}
}
private string _lineOne;
public string LineOne
{
get
{
return _lineOne;
}
set
{
if (value != _lineOne)
{
_lineOne = value;
NotifyPropertyChanged("LineOne");
}
}
}
private string _lineTwo;
public string LineTwo
{
get
{
return _lineTwo;
}
set
{
if (value != _lineTwo)
{
_lineTwo = value;
NotifyPropertyChanged("LineTwo");
}
}
}
private string _lineThree;
public string LineThree
{
get
{
return _lineThree;
}
set
{
if (value != _lineThree)
{
_lineThree = value;
NotifyPropertyChanged("LineThree");
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(String propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (null != handler)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
}
You should do this
Items.Add( new ItemViewModel
{
LineOne = check.ClientName,
LineTwo = check.NSMDateTime.ToString(),
LineThree = check.HaveRead.ToString(),
MyappId = check.MonitoringID
});
Use ToString();
or cast to string
Related
I have a JSON class file which contains three classes, all of which follow this structure:
public class ManifestJSON : INotifyPropertyChanged
{
[JsonProperty("dataType")]
private string dataType;
public string DataType
{
get
{
return dataType;
}
set
{
if(dataType != value)
{
dataType = value;
RaisePropertyChanged("DataType");
}
}
}
[JsonProperty("ttl")]
private int time_to_live;
public int Time_To_Live
{
get
{
return time_to_live;
}
set
{
if (time_to_live != value)
{
time_to_live = value;
RaisePropertyChanged("Time_To_Live");
}
}
}
[JsonProperty("serial")]
private long serial;
public long Serial
{
get
{
return serial;
}
set
{
if (serial != value)
{
serial = value;
RaisePropertyChanged("Serial");
}
}
}
[JsonProperty("modifiedIso8601")]
private string modifiedIso8601;
public string ModifiedIso8601
{
get
{
return modifiedIso8601;
}
set
{
if (modifiedIso8601 != value)
{
modifiedIso8601 = value;
RaisePropertyChanged("ModifiedIso8601");
}
}
}
[JsonProperty("modifiedTimestamp")]
private long modifiedTimestamp;
public long ModifiedTimestamp
{
get
{
return modifiedTimestamp;
}
set
{
if (modifiedTimestamp != value)
{
modifiedTimestamp = value;
RaisePropertyChanged("ModifiedTimestamp");
}
}
}
[JsonProperty("timezone")]
private string timezone;
public string Timezone
{
get
{
return timezone;
}
set
{
if (timezone != value)
{
timezone = value;
RaisePropertyChanged("Timezone");
}
}
}
[JsonProperty("exports")]
private ObservableCollection<ManifestItem> manifest_Items;
public ObservableCollection<ManifestItem> Manifest_Items
{
get
{
return manifest_Items;
}
set
{
if (manifest_Items != value)
{
manifest_Items = value;
RaisePropertyChanged("Manifest_Items");
}
}
}
//Event handling
public event PropertyChangedEventHandler PropertyChanged;
private void RaisePropertyChanged(string property)
{
Console.WriteLine("Updated");
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(property));
}
}
In another class, I've created a global instance of type ManifestJSON
public ManifestJSON manifestData;
which is filled by deserializing a JSON string into this object using the DeserializeObject method from the Newtonsoft.json library like so:
manifestData = JsonConvert.DeserializeObject<ManifestJSON>(JSONString).
This fills the ManifestJSON class successfully, but none of my property methods or events are triggering. What am I doing wrong here?
If you want to update your existing data-bound ManifestJSON object, you should not replace this one with a new object but de-serialize the JSON string into new object and then set the properties of the existing manifestData object:
var newData = JsonConvert.DeserializeObject<ManifestJSON>(JSONString);
manifestData.DataType = newData.DataType;
manifestData.Time_To_Live = newData.Time_To_Live;
manifestData.Serial = newData.Serial;
//...
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;
}
}
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 am writing a boring application to manage patients and their clinic history. I used SQLite combined with DbLinq libraries and DbMetal code generation utility. Here are two classes from the genereated code extracted from the underlying database:
[Table(Name="main.Patients")]
public partial class Patient : System.ComponentModel.INotifyPropertyChanging, System.ComponentModel.INotifyPropertyChanged
{
private static System.ComponentModel.PropertyChangingEventArgs emptyChangingEventArgs = new System.ComponentModel.PropertyChangingEventArgs("");
private long _birthday;
private string _firstName;
private int _hasChildren;
private System.Nullable<int> _id;
private int _isMarried;
private string _lastName;
private string _profession;
private EntitySet<ClinicCase> _clinicCases;
private EntitySet<PatientAddress> _patientsAddresses;
private EntitySet<PatientPhoneNumber> _patientsPhoneNumbers;
#region Extensibility Method Declarations
partial void OnCreated();
partial void OnBirthdayChanged();
partial void OnBirthdayChanging(long value);
partial void OnFirstNameChanged();
partial void OnFirstNameChanging(string value);
partial void OnHasChildrenChanged();
partial void OnHasChildrenChanging(int value);
partial void OnIDChanged();
partial void OnIDChanging(System.Nullable<int> value);
partial void OnIsMarriedChanged();
partial void OnIsMarriedChanging(int value);
partial void OnLastNameChanged();
partial void OnLastNameChanging(string value);
partial void OnProfessionChanged();
partial void OnProfessionChanging(string value);
#endregion
public Patient()
{
_clinicCases = new EntitySet<ClinicCase>(new Action<ClinicCase>(this.ClinicCases_Attach), new Action<ClinicCase>(this.ClinicCases_Detach));
_patientsAddresses = new EntitySet<PatientAddress>(new Action<PatientAddress>(this.PatientsAddresses_Attach), new Action<PatientAddress>(this.PatientsAddresses_Detach));
_patientsPhoneNumbers = new EntitySet<PatientPhoneNumber>(new Action<PatientPhoneNumber>(this.PatientsPhoneNumbers_Attach), new Action<PatientPhoneNumber>(this.PatientsPhoneNumbers_Detach));
this.OnCreated();
}
[Column(Storage="_birthday", Name="Birthday", DbType="integer", AutoSync=AutoSync.Never, CanBeNull=false)]
[DebuggerNonUserCode()]
public long BirthdayBinaryDate
{
get
{
return this._birthday;
}
set
{
if ((_birthday != value))
{
this.OnBirthdayChanging(value);
this.SendPropertyChanging();
this._birthday = value;
this.SendPropertyChanged("Birthday");
this.OnBirthdayChanged();
}
}
}
[Column(Storage="_firstName", Name="FirstName", DbType="text", AutoSync=AutoSync.Never, CanBeNull=false)]
[DebuggerNonUserCode()]
public string FirstName
{
get
{
return this._firstName;
}
set
{
if (((_firstName == value)
== false))
{
this.OnFirstNameChanging(value);
this.SendPropertyChanging();
this._firstName = value;
this.SendPropertyChanged("FirstName");
this.OnFirstNameChanged();
}
}
}
[Column(Storage="_hasChildren", Name="HasChildren", DbType="integer", AutoSync=AutoSync.Never, CanBeNull=false)]
[DebuggerNonUserCode()]
public int HasChildren
{
get
{
return this._hasChildren;
}
set
{
if ((_hasChildren != value))
{
this.OnHasChildrenChanging(value);
this.SendPropertyChanging();
this._hasChildren = value;
this.SendPropertyChanged("HasChildren");
this.OnHasChildrenChanged();
}
}
}
[Column(Storage="_id", Name="ID", DbType="integer", IsPrimaryKey=true, IsDbGenerated=true, AutoSync=AutoSync.OnInsert)]
[DebuggerNonUserCode()]
public System.Nullable<int> ID
{
get
{
return this._id;
}
set
{
if ((_id != value))
{
this.OnIDChanging(value);
this.SendPropertyChanging();
this._id = value;
this.SendPropertyChanged("ID");
this.OnIDChanged();
}
}
}
[Column(Storage="_isMarried", Name="IsMarried", DbType="integer", AutoSync=AutoSync.Never, CanBeNull=false)]
[DebuggerNonUserCode()]
public int IsMarried
{
get
{
return this._isMarried;
}
set
{
if ((_isMarried != value))
{
this.OnIsMarriedChanging(value);
this.SendPropertyChanging();
this._isMarried = value;
this.SendPropertyChanged("IsMarried");
this.OnIsMarriedChanged();
}
}
}
[Column(Storage="_lastName", Name="LastName", DbType="text", AutoSync=AutoSync.Never, CanBeNull=false)]
[DebuggerNonUserCode()]
public string LastName
{
get
{
return this._lastName;
}
set
{
if (((_lastName == value)
== false))
{
this.OnLastNameChanging(value);
this.SendPropertyChanging();
this._lastName = value;
this.SendPropertyChanged("LastName");
this.OnLastNameChanged();
}
}
}
[Column(Storage="_profession", Name="Profession", DbType="text", AutoSync=AutoSync.Never)]
[DebuggerNonUserCode()]
public string Profession
{
get
{
return this._profession;
}
set
{
if (((_profession == value)
== false))
{
this.OnProfessionChanging(value);
this.SendPropertyChanging();
this._profession = value;
this.SendPropertyChanged("Profession");
this.OnProfessionChanged();
}
}
}
#region Children
[Association(Storage="_clinicCases", OtherKey="PatientID", ThisKey="ID", Name="fk_ClinicCases_0")]
[DebuggerNonUserCode()]
public EntitySet<ClinicCase> ClinicCases
{
get
{
return this._clinicCases;
}
set
{
this._clinicCases = value;
}
}
[Association(Storage="_patientsAddresses", OtherKey="PatientID", ThisKey="ID", Name="fk_PatientsAddresses_0")]
[DebuggerNonUserCode()]
public EntitySet<PatientAddress> Addresses
{
get
{
return this._patientsAddresses;
}
set
{
this._patientsAddresses = value;
}
}
[Association(Storage="_patientsPhoneNumbers", OtherKey="PatientID", ThisKey="ID", Name="fk_PatientsPhoneNumbers_0")]
[DebuggerNonUserCode()]
public EntitySet<PatientPhoneNumber> PhoneNumbers
{
get
{
return this._patientsPhoneNumbers;
}
set
{
this._patientsPhoneNumbers = value;
}
}
#endregion
public event System.ComponentModel.PropertyChangingEventHandler PropertyChanging;
public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;
protected virtual void SendPropertyChanging()
{
System.ComponentModel.PropertyChangingEventHandler h = this.PropertyChanging;
if ((h != null))
{
h(this, emptyChangingEventArgs);
}
}
protected virtual void SendPropertyChanged(string propertyName)
{
System.ComponentModel.PropertyChangedEventHandler h = this.PropertyChanged;
if ((h != null))
{
h(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));
}
}
#region Attachment handlers
private void ClinicCases_Attach(ClinicCase entity)
{
this.SendPropertyChanging();
entity.Patient = this;
}
private void ClinicCases_Detach(ClinicCase entity)
{
this.SendPropertyChanging();
entity.Patient = null;
}
private void PatientsAddresses_Attach(PatientAddress entity)
{
this.SendPropertyChanging();
entity.Patient = this;
}
private void PatientsAddresses_Detach(PatientAddress entity)
{
this.SendPropertyChanging();
entity.Patient = null;
}
private void PatientsPhoneNumbers_Attach(PatientPhoneNumber entity)
{
this.SendPropertyChanging();
entity.Patient = this;
}
private void PatientsPhoneNumbers_Detach(PatientPhoneNumber entity)
{
this.SendPropertyChanging();
entity.Patient = null;
}
#endregion
}
[Table(Name="main.PatientsAddresses")]
public partial class PatientAddress : System.ComponentModel.INotifyPropertyChanging, System.ComponentModel.INotifyPropertyChanged
{
private static System.ComponentModel.PropertyChangingEventArgs emptyChangingEventArgs = new System.ComponentModel.PropertyChangingEventArgs("");
private string _address;
private string _domicileStatus;
private System.Nullable<int> _patientID;
private EntityRef<Patient> _patients = new EntityRef<Patient>();
#region Extensibility Method Declarations
partial void OnCreated();
partial void OnAddressChanged();
partial void OnAddressChanging(string value);
partial void OnDomicileStatusChanged();
partial void OnDomicileStatusChanging(string value);
partial void OnPatientIDChanged();
partial void OnPatientIDChanging(System.Nullable<int> value);
#endregion
public PatientAddress()
{
this.OnCreated();
}
[Column(Storage="_address", Name="Address", DbType="text", IsPrimaryKey=true, AutoSync=AutoSync.Never)]
[DebuggerNonUserCode()]
public string Address
{
get
{
return this._address;
}
set
{
if (((_address == value)
== false))
{
this.OnAddressChanging(value);
this.SendPropertyChanging();
this._address = value;
this.SendPropertyChanged("Address");
this.OnAddressChanged();
}
}
}
[Column(Storage="_domicileStatus", Name="DomicileStatus", DbType="text", AutoSync=AutoSync.Never)]
[DebuggerNonUserCode()]
public string DomicileStatus
{
get
{
return this._domicileStatus;
}
set
{
if (((_domicileStatus == value)
== false))
{
this.OnDomicileStatusChanging(value);
this.SendPropertyChanging();
this._domicileStatus = value;
this.SendPropertyChanged("DomicileStatus");
this.OnDomicileStatusChanged();
}
}
}
[Column(Storage="_patientID", Name="PatientID", DbType="integer", IsPrimaryKey=true, IsDbGenerated=true, AutoSync=AutoSync.Never)]
[DebuggerNonUserCode()]
public System.Nullable<int> PatientID
{
get
{
return this._patientID;
}
set
{
if ((_patientID != value))
{
if (_patients.HasLoadedOrAssignedValue)
{
throw new System.Data.Linq.ForeignKeyReferenceAlreadyHasValueException();
}
this.OnPatientIDChanging(value);
this.SendPropertyChanging();
this._patientID = value;
this.SendPropertyChanged("PatientID");
this.OnPatientIDChanged();
}
}
}
#region Parents
[Association(Storage="_patients", OtherKey="ID", ThisKey="PatientID", Name="fk_PatientsAddresses_0", IsForeignKey=true)]
[DebuggerNonUserCode()]
public Patient Patient
{
get
{
return this._patients.Entity;
}
set
{
if (((this._patients.Entity == value)
== false))
{
if ((this._patients.Entity != null))
{
Patient previousPatients = this._patients.Entity;
this._patients.Entity = null;
previousPatients.Addresses.Remove(this);
}
this._patients.Entity = value;
if ((value != null))
{
value.Addresses.Add(this);
_patientID = value.ID;
}
else
{
_patientID = null;
}
}
}
}
#endregion
public event System.ComponentModel.PropertyChangingEventHandler PropertyChanging;
public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;
protected virtual void SendPropertyChanging()
{
System.ComponentModel.PropertyChangingEventHandler h = this.PropertyChanging;
if ((h != null))
{
h(this, emptyChangingEventArgs);
}
}
protected virtual void SendPropertyChanged(string propertyName)
{
System.ComponentModel.PropertyChangedEventHandler h = this.PropertyChanged;
if ((h != null))
{
h(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));
}
}
}
I use the following code to add an address to a patient:
PatientAddress address = new PatientAddress();
address.Address = txtAddress.Text;
address.DomicileStatus = cmbDomicileStatus.Text;
currentPatient.Addresses.Add(address);
Database.Source.PatientsAddresses.InsertOnSubmit(address);
Database.Source.SubmitChanges();
Database.Source is an instance of the class that extends DataContext in the generated code. On SubmitChanges, I receive this exception:
"Equal operator is not defined between Nullable(Of Int32) and Int32."
The message is not reported word by word, but the meaning is the same. The stack trace point to DbLinq code, more precisely to line 709 of source file DbLinq.Data.Linq.DataContext.cs. You can find the source files here: http://dblinq.codeplex.com/SourceControl/changeset/view/16800#314775 (under the body of the method SetEntityRefQueries(object entity)).
I see that the problem comes when comparing a foreign key value with a constant in an expression tree, but I couln't manage to get other information on that. Can you help me find the issue?
N.B.: the field address.PatientID (foreign key) is actually set to the correct value before the invocation of SubmitChanges.
As I mentioned in the comment above (which I'm repeating here so I can link images), your primary key should not be nullable. There should be a property in your mapping that you can change to set it, although I don't use DbLinq, so I can't give you a screenshot of it directly. Instead, here it is in the LINQ-2-SQL DBML designer (left) and the Entity Framework EDMX designer (right).
I'm not as sure about your deletion problem - that seems like it should work to me. Can you edit your question to include the whole block of your deletion code? As a preliminary guess, you're either creating a new object (instead of loading one) and then trying to delete it, or you're deleting the association without deleting the object.
As a general rule, I never delete from a database when I can avoid it - I just mark inactive. It's much easier to "undelete" that way.
Did you try: address.Patient = currentPatient
instead of: currentPatient.Addresses.Add(address)?
PatientAddress address = new PatientAddress();
address.Address = txtAddress.Text;
address.DomicileStatus = cmbDomicileStatus.Text;
address.Patient = currentPatient;
Database.Source.PatientsAddresses.InsertOnSubmit(address);
Database.Source.SubmitChanges();
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.