开发者

Automatically create correct class of object when pulling data with LINQ

开发者 https://www.devze.com 2023-03-19 18:55 出处:网络
Sorry for the bad title, I really开发者_StackOverflow社区 don\'t know how to word it better. I have a SQL table named Posts and a class named Post. A post can be multiple things such as a Thread or a

Sorry for the bad title, I really开发者_StackOverflow社区 don't know how to word it better.

I have a SQL table named Posts and a class named Post. A post can be multiple things such as a Thread or a ThreadReply, which are subclasses of Post but are all stored in the same Post table. To identify the type of Post it has a PostType field.

[Table(Name = "Posts")]
public class Post
{
    [Column(IsPrimaryKey = true, IsDbGenerated = true, AutoSync = AutoSync.OnInsert)]
    public int Id { get; set; }

    [Column]
    public PostType Type { get; set; }

    // ...
 }

 public class Thread : Post { /* ... */ };
 public class ThreadReply : Post { /* ... */ };

I use this to get the posts from the database in my IPostsRepository:

 db.GetTable<Post>(); // IQueryable<Post>

However they are all instantiated as Post (obviously). I want them to be instantiated based on their PostType, so that things like Thread t = p as Thread; will work.

Any ideas?


Use IsDiscriminator attribute to define table per Class Hierarchy.

0

精彩评论

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