开发者

InsertOnSubmit with interfaces (LINQ to SQL)

In our code we have:

public interface ILogMagazine
{
 string Text { get; set; }

 DateTime DateAndTime { get; set; }

 string 开发者_如何学JAVADetailMessage { get; set; }
}

SimpleDataContext: DataContext
{
  public Table<ILogMagazine> LogMagaines
  {
    get { return GetTable<ILogMagazine>(); }
  }
}

We try to:

DataContext db = new SimpleDataContext("...");

ILogMagazine lg = new LogMagazine()
{
 Text = "test",
 DateAndTime = DateTime.Now,
 DetailMessage = "test",
};

db.LogMagazines.InsertOnSubmit(lg); // Exception thrown
db.SubmitChanges();

Exception: System.InvalidOperationException: The type 'DataLayer.ILogMagazine' is not mapped as a Table..


How we can solve this problem?


The error is because you haven't applied the [Table] attribute (normally it'd go on a class type, in your case the interface type), but I don't see it working even if you did. That's how the mapping is done- when you call GetTable, it looks for the Table attribute to know where to insert/query the data from.

That said, I'm pretty sure you can't do this with an interface. The type on GetTable has to be concrete, because it uses the generic arg passed (or inferred) on GetTable to know what object to create for a query. While it might technically be able to work for inserts, the same GetTable is used for both inserts and queries- which it most certainly won't work for. Same reason XmlSerializer and DataContractSerializer don't work with interfaces.

You'll always need a concrete type, but your entity types can still implement interfaces. I'm guessing you're trying to shuttle these around somewhere (service layer, perhaps), and you'll probably need to rethink that a bit.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜