'Unable to cast object of type 'System.Data.Linq.Table`1 to type 'System.Collections.Generic.List

71 Views Asked by At

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;
    }
}
1

There are 1 best solutions below

0
Chris Schaller On

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 an IListSource and not actually a list, so you can't directly Add records to it, instead you need to Append or Attach them.

In this case I would use Attach so that Append doesn't track the record as a new record to later try to insert into the database.