Using delete on a LINQ to Sql Data Context with an Interface - 'Interface is not mapped as a table'
I have three entities in my data context which inherit IFileData
, but I want just a sin开发者_如何学编程gle delete method. How can this be achieved?
The code below give the error The type "IFileData" is not mapped as a Table
.
public void ImageDelete<T>(T instance) where T : class, IFileData
{
using (var db = this.CreateDataContext())
{
db.GetTable<T>().DeleteOnSubmit(instance);
db.SubmitChanges();
}
}
The only solution I have so far is to do a switch on the .GetType()
which is a bit messy.
Thanks!
Solution:
As Marc mentioned, I used dynamic
in the calling method:
ImageDelete((dynamic)(instance as IFileData));
You could build the Expression
manually, using the actual T
? Untested (since that Delete
doesn't exist?), but something like:
var param = Expression.Parameter(typeof(T), "x");
var lambda = Expression.Lambda<Func<T, bool>>(
Expression.Equal(
Expression.Property(param, "Key"),
Expression.Constant(instance.Key)
), param);
This then isn't bound to IFileData
, but to T
. It will fail, however, if IFileData.Key
is implemented via explicit interface implementation - there must be an obvious Key
field/property on T
.
Then:
var table = db.GetTable<T>();
var obj = table.SingleOrDefault(lambda);
if(obj != null) table.DeleteOnSubmit(obj);
db.SubmitChanges();
精彩评论