建模多种帖子类型

时间:2012-11-19 05:44:57

标签: c# models

让我举一个很好的例子说明我的问题。

假设我正在构建一个应用程序,其中许多用户可以发布不同类型的“帖子”(即照片,状态等)。让我们在这种情况下使用照片和状态。

我将向您展示我目前如何为我的数据建模,以及是否可以改进(以及我做错了什么)

我有一个通用的Post类:

public class Post<T>
{
    public Guid Id { get; set; }

    public User Owner { get; set; }

    public DateTime CreatedDate { get; set; }

    public PostType Type { get; set; }

    public T Data { get; set; }
}

然后我有一个PostType枚举:

public enum PostType
{
    Photo,
    Status
}

然后我有各自的照片和状态类

public class Photo
{
    public string Url { get; set; }

    public int Width { get; set; }

    public int Height { get; set; }
}

public class Status
{
    public string Text { get; set; }
}

我知道如果我追求当前的解决方案来建模这些数据,我会遇到问题。

我已经遇到了一些痛点,例如如何返回最新的25篇帖子,无论类型,还有如何按ID返回特定帖子没有指定帖子的类型(因为用户不应该关心。

我是否完全错误地建模我的数据?如果是这样,你有任何改进建议吗?

2 个答案:

答案 0 :(得分:1)

你的两个问题都可以通过一个独立于帖子类型的基类来解决:

public abstract class Post
{
    public Guid Id { get; set; }

    public User Owner { get; set; }

    public DateTime CreatedDate { get; set; }

    public PostType Type { get; set; }
}

您的Post课程可以继承它:

public class Post<T> : Post
{
    public T Data { get; set; }
}

应该返回任何类型帖子的方法仍然可以返回正确的类型,但调用者将以基本Post类型访问它们并在需要时投射它们:

Post GetPostById(int id);
IEnumerable<Post> GetLatestPosts(int count);

答案 1 :(得分:0)

  

如何返回最新的25个帖子,无论类型

你不能,因为在你的设计中,PhotoStatus之间没有任何共同点,你有一个通用Post<T>,但这里T可以不要一批进行。更好的设计是这样的:

public interface IPostable
{
    Guid Id { get; set; }

    public DateTime CreatedDate { get; set; }

    PostType PostType { get; }
}

public class Photo : IPostable
{
    //special properties for photo
    public string Url { get; set; }

    //implement the interface
    public PostType PostType { get { return PostType.Photo; } }
}

public class Status : IPostable
{
    public string Text { get; set; }
    public PostType PostType { get { return PostType.Status; } }
}

然后,您总是批量处理IPostable

  

如何按ID返回特定帖子

根据上面的设计,您可以轻松地通过其id获取IPostable实例,因为id是其属性之一,并通过判断其PostType属性返回强类型实例:

public IPostable GetPost(Guid id)
{
    //id is a property of IPostable, so everything is easy
}

//you can easily get the real type
public T GetPost<T>(Guid id)
{
    IPostable post = GetThePostFirst();
    if (post.PostType == PostType.Photo) return (Photo)IPostable;
    //etc.
}
相关问题