0

In my application I have Folders that can contain other Folders. They have all sorts of properties like this:

public class Folder
    {
        public Folder()
        {
            Sets = new Collection<Set>();
            Folders = new Collection<Folder>();
            Stage = Stage.one;
            IsArchived = false;
            DateCreated = DateTime.Now;
            }

        // Primitive Properties 

        [Required]
        [Key]
        public virtual int FolderId { get; set; }

        public virtual int? ParentFolderId { get; set; }

        [ForeignKey("ParentFolderId")]
        public virtual Folder ParentFolder { get; set; }

        [Required]
        public int UserId { get; set; }

        [Required]
        public virtual string Title { get; set; }

        public virtual string Details { get; set; }

        [Required]
        public virtual Stage Stage { get; set; }

        [Required]
        public virtual bool IsArchived { get; set; }

        [Required]
        public virtual DateTime DateCreated { get; set; }

        [ForeignKey("FolderId")]
        public virtual ICollection<Set> Sets { get; set; }

        [ForeignKey("ParentFolderId")]
        public virtual ICollection<Folder> Folders { get; set; }

    }

Now, each User of the application has a "Home Folder" - a starting point. The Home Folder doesn't need half of the above properties however. I figure I have two options:

1) Use this entity and just add "isHomeFolder" as a property. This is simple but means I'll be sending blank [Required] properties over the wire for JSON requests - Home Folders don't have a title, can't be archived, etc.

2) Create another entity with just the required fields and duplicate the required properties there. This just doesn't seem very DRY, but feels better than the first option.

As a beginner programmer I'm not sure if there are any other options. Is there a standard approach/solution here?

In case it matters, I'm building on Entity Framework Code-First + WebAPI.

4

3 回答 3

0

2) 创建另一个仅包含必填字段的实体,并在那里复制所需的属性。这看起来不是很干,但感觉比第一个选项好。

这就是为什么 ViewModel 对于避免不必要(过度)发布、发布您不需要的值很重要的原因。此外,为了避免实体中的必填字段,您不希望它们或它们不适用于“特定视图”。实体不一定转化为单个视图。你的案例就是一个活生生的例子。

这里有标准方法/解决方案吗?

正如我所提到的,创建一个视图模型并仅复制您需要为其捕获输入的属性。即使您将数据注释放在相同的属性上,这也不会重复您自己。视图模型上的数据注释用于视图验证。您实体上的注释用于域验证。这不是重复,IMO,因为您的 UI 与您的域是不同的层。

于 2013-04-16T02:38:54.293 回答
0

也许您应该创建一个包含公共属性的类。然后,您可以使用两个实现从第一个继承的类。

于 2013-04-16T02:42:02.840 回答
0

这取决于与文件夹总数相比,您将拥有多少个主文件夹。如果您将拥有比主文件夹更多的二级文件夹(并且您很可能会),那么为什么仅仅为了 10% 或 20% 或请求而费心实施另一个结构。

至于必填字段为空 - 只需使用一些不会在服务器端解析的默认值,你很好;)。

于 2013-04-16T08:38:57.940 回答