Thrown Exception
System.InvalidCastException: 'Unable to cast object of type 'System.Data.Linq.Table`1[SalesWithLinq.DAL.UnitName]' to type 'System.Collections.Generic.List`1[SalesWithLinq.DAL.UnitName]'.'
I want to add unit name inside repository lookUpEdit and save it once i leave the cell the data is successfully saved in data base but when reach casting line the exception thrown
RepositoryItemLookUpEdit repoUOM = new RepositoryItemLookUpEdit(); // field of form class
repoUOM.DisplayMember = "Name"; // inside form load event
repoUOM.ValueMember = "ID"; // inside form load event
repoUOM.TextEditStyle = DevExpress.XtraEditors.Controls.TextEditStyles.Standard; // inside form load event
private void RepoUOM_ProcessNewValue(object sender, DevExpress.XtraEditors.Controls.ProcessNewValueEventArgs e)
{
if (e.DisplayValue is string value && value.Trim() != string.Empty)
{
var NewObject = new UnitName() { Name = value.Trim() };
using (var db = new dbDataContext())
{
db.UnitNames.InsertOnSubmit(NewObject);
db.SubmitChanges();
}
((List<UnitName>)repoUOM.DataSource).Add(NewObject); // exception thrown here
e.Handled = true;
}
}
You cannot explicitly cast a type like that unless it is supported through inheritance, covariance or an explicit type conversion is defined.
You could try explicitly casting to
Table<UnitName>as that is the underlying type, see Linq Table but the table is actually anIListSourceand not actually a list, so you can't directlyAddrecords to it, instead you need toAppendorAttachthem.In this case I would use
Attachso thatAppenddoesn't track the record as a new record to later try to insert into the database.