【问题标题】:How can I override the properties in partial class?如何覆盖部分类中的属性?
【发布时间】:2012-08-02 04:45:45
【问题描述】:

我正在开发一个 MVC 应用程序,我在开发它时使用了 EF 4.0。我已经从模型中创建了类。现在,我想为 MVC 制作的每个类添加更多类。

例如。在下面的代码中,我得到了类位置。 现在,我想再创建一个类(部分类)如何覆盖部分类中的属性?

如何做到这一点?

namespace Entities
{
   public partial class Location
   {               
       public int Id { get; set; }

       public string Name { get; set; }
       public string Remark { get; set; }      
       public string State { get; set; }       
       public string Region { get; set; }
       public string PinCode { get; set; }

       public virtual ICollection<Comment> Comments { get; set; }
   }    
}

【问题讨论】:

  • “覆盖部分类中的属性”是什么意思?
  • 我想对部分类中的属性进行一些验证。例如。我想在部分类中添加以下代码 '[StringLength(50, ErrorMessage = "Region can accept maximum 50 characters.")] public string Region { get;放; }'
  • 为什么你不能进入你现在的班级?
  • 好吧,如果我在当前类中编写它并且如果我再次从模型生成类,那么类会被覆盖并且所有验证都会丢失。而且我的结构还不稳定。所以最好在部分类中编写。

标签: asp.net-mvc model-view-controller entity-framework-4 entity


【解决方案1】:

你可以在带有接口的部分类中进行属性修饰

如果您生成了以下类(通过任何自定义工具)

public partial class Location
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Remark { get; set; }
    public string State { get; set; }
    public string Region { get; set; }
    public string PinCode { get; set; }
    public virtual ICollection<Comment> Comments { get; set; }
}

您可以通过创建一个新接口和一个新的分部类来为生成的类中的属性添加注释(无需修改生成的文件),如下所示

    public interface ILocation
    {
        [StringLength(50, ErrorMessage = "Region can accept maximum 50 characters.")]
        string Region { get; set; }
    }

    public partial class Location :ILocation
    {
    }

【讨论】:

  • 谢谢,但我在哪里可以写这段代码?在哪个级别 ?在部分课程中(新课程)?我不应该在生成的类中添加任何东西,因为它会生成很多次,直到我的结构没有得到修复。
  • @nilesh1foru ive 更新了我的答案以适用于您的具体案例
  • 我没有告诉你在同一个程序集中的全新文件中添加接口和新的部分类
  • 我不知道如何以不同的方式向您解释这一点,将底部的两件事放在一个全新的文件中,当您生成原始文件时,它将保留该属性
  • 这不适用于验证,因为它将在生成的代码块处被覆盖,并且注释也将被覆盖。这意味着您的界面中没有任何注释生效
【解决方案2】:

如果您只需要验证,则可以使用所谓的元数据类型。

详细教程是here。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-09-05
    • 2011-04-22
    • 2016-11-06
    • 2021-12-30
    • 1970-01-01
    • 2018-02-06
    • 2013-09-24
    • 2018-12-10
    相关资源
    最近更新 更多