【问题标题】:MVC 4 EF5 Database First set Default Values in Partial ClassMVC 4 EF5 数据库首先在部分类中设置默认值
【发布时间】:2013-11-25 22:35:45
【问题描述】:

我是 MVC 的新手,并试图弄清楚如何为部分类设置默认值。我已经搜索了 2 天,但没有任何工作。 Here 是一个假定的解决方案,但它对我不起作用。我还尝试了 [DefaultValue(10)] 数据注释。

这是从 edmx 文件创建的自动生成的部分类

//------------------------------------------------------------------------------
// <auto-generated>
//    This code was generated from a template.
//
//    Manual changes to this file may cause unexpected behavior in your application.
//    Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace OTIS.Models.Admin
{
    using System;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;

    public partial class Company
    {
        public Company()
        {
            this.Facilities = new HashSet<Facility>();
        }

        public int CompanyID { get; set; }

        [Required]
        [Display(Name = "Company Name")]
        public string CompanyName { get; set; }

        public string Address1 { get; set; }
        public string Address2 { get; set; }
        public string City { get; set; }
        public string State { get; set; }
        public string PostalCode { get; set; }
        public decimal ItemMargin { get; set; }
        public decimal ServicesMargin { get; set; }
        public decimal InvoiceTimeIncrement { get; set; }
        public decimal CashDiscountPct { get; set; }
        public decimal BaseServiceHourlyRate { get; set; }
        public decimal HourlyPremiumRush { get; set; }
        public decimal HourlyPremiumLate { get; set; }
        public decimal HourlyPremiumCustomerMaterial { get; set; }
        public int CreatedByID { get; set; }
        public System.DateTime CreatedOn { get; set; }
        public int ModifiedBy { get; set; }
        public System.DateTime ModifiedOn { get; set; }

        public virtual UserProfile UserProfile { get; set; }
        public virtual UserProfile UserProfile1 { get; set; }
        public virtual ICollection<Facility> Facilities { get; set; }
    }
}

这是我为添加注释而创建的部分类。

namespace OTIS.Models.Admin
{
    [MetadataType(typeof(CompanyMD))]
    public partial class Company
    {

        //public Company()
        //{
        //    //private System.DateTime _currentDateTime = DateTime.Now;
        //    ////Set Default Values
        //    //CreatedByID = (int)Membership.GetUser().ProviderUserKey;
        //    //CreatedOn = _currentDateTime;
        //    //ModifiedBy = (int)Membership.GetUser().ProviderUserKey;
        //    //ModifiedOn = _currentDateTime;
        //}

        public string FullAddress
        {
            get
            {
                return this.City + ", " + this.State + " " + this.PostalCode;
            }
        }

        public class CompanyMD
        {
            private System.DateTime _currentDateTime = DateTime.Now;
            private int _currentUser = (int)Membership.GetUser().ProviderUserKey;


            [Display(Name = "Company ID")]
            public int CompanyID { get; set; }

            [Required]
            [Display(Name = "Company Name")]
            public string CompanyName { get; set; }

            [Display(Name = "Address")]
            public string Address1 { get; set; }

            [Display(Name = "Address 2")]
            public string Address2 { get; set; }

            public string City { get; set; }
            public string State { get; set; }

            [Display(Name = "Zip")]
            public string PostalCode { get; set; }

            [Display(Name = "Address")]
            public string FullAddress { get; set; }

            [Display(Name = "Material Margin")]
            public decimal ItemMargin { get; set; }

            [Display(Name = "Overtime Margin")]
            public decimal ServicesMargin { get; set; }

            [Display(Name = "Invoice Hour Increment")]
            public decimal InvoiceTimeIncrement { get; set; }

            private decimal _cashDiscountPct;

            [Display(Name = "Cash Discount %")]
            [DisplayFormat(DataFormatString = "{0:P2}")]
            public decimal CashDiscountPct
            {
                get { return _cashDiscountPct; }
                set { _cashDiscountPct = value/100; }
            }

            [Display(Name = "Base Hourly Rate ($/Hr)")]
            [DataType(DataType.Currency), DisplayFormat(DataFormatString = "{0:C2}", ApplyFormatInEditMode = true)]
            public decimal BaseServiceHourlyRate { get; set; }

            [Display(Name = "Rush Premium ($/Hr)")]
            [DataType(DataType.Currency), DisplayFormat(DataFormatString = "{0:C2}", ApplyFormatInEditMode = true)]
            public decimal HourlyPremiumRush { get; set; }

            [Display(Name = "Late Premium ($/Hr)")]
            [DataType(DataType.Currency), DisplayFormat(DataFormatString = "{0:C2}", ApplyFormatInEditMode = true)]
            [DefaultValue(75)]
            public decimal HourlyPremiumLate { get; set; }

            [Display(Name = "Cust Material Premium ($/Hr)")]
            [DataType(DataType.Currency), DisplayFormat(DataFormatString = "{0:C2}", ApplyFormatInEditMode = true)]
            public decimal HourlyPremiumCustomerMaterial { get; set; }

            [Display(Name = "Created By")]
            public int CreatedByID { get; set; }
            //{
            //    get { return _currentUser; }
            //    set { _currentUser = value; }
            //}

            [Display(Name = "Created On")]
            [DatabaseGenerated(DatabaseGeneratedOption.Computed)]
            //[DataType(DataType.Date), DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
            public System.DateTime CreatedOn 
            {
                get { return _currentDateTime; }
                set { _currentDateTime = value; }
            }

            [Display(Name = "Modified By")]
            public int ModifiedBy { get; set; }
            //{
            //    get { return _currentUser; }
            //    set { _currentUser = value; }
            //}

            [Display(Name = "Modified On")]
            public System.DateTime ModifiedOn
            {
                get { return _currentDateTime; }
                set { _currentDateTime = value; }
            }

        }

    }
}

然后在我的控制器中,我实例化了一个新的类实例来初始化它,但是我设置的值没有被设置。

//
        // GET: /Company/Create

        public ActionResult Create()
        {
            ViewBag.CreatedByID = new SelectList(db.UserProfiles, "UserId", "UserName");
            ViewBag.ModifiedBy = new SelectList(db.UserProfiles, "UserId", "UserName");
            Company newCompany = new Company();
            return View(newCompany);
        }

【问题讨论】:

  • 注意:如果我取消注释 public Company() 行,我得到的错误是:类型 'OTIS.Models.Admin.Company' 已经定义了一个名为 'Company' 的成员,具有相同的参数类型

标签: asp.net-mvc-4 entity-framework-5 ef-database-first


【解决方案1】:

对不起,这太晚了,但我自己解决了一个类似的情况。

我认为问题在于您如何引用部分类。它应该是对没有代码的部分类的空引用。 EF 使用此“声明”将您的部分类链接到您的元数据类。因此,您的元数据类应如下所示:

namespace OTIS.Models.Admin
{
    [MetadataType(typeof(CompanyMD))]
    public partial class Company
    {}  // <-- note the close bracket!

    public class CompanyMD
    {
        private System.DateTime _currentDateTime = DateTime.Now;
        private int _currentUser = (int)Membership.GetUser().ProviderUserKey;

        public string FullAddress
        {
            get
            {
                return this.City + ", " + this.State + " " + this.PostalCode;
            }
        }

        [Display(Name = "Company ID")]
        public int CompanyID { get; set; }
        [Required]
        [Display(Name = "Company Name")]
        public string CompanyName { get; set; }

        // ....etc.... removed for brevity

    } // close metadata class
} // close namespace

希望这会有所帮助!

【讨论】:

  • 感谢您的回复 jpg0002,但我不想要一个涉及 EF 更改自动生成的类的解决方案,因为它肯定会被覆盖。我最终不得不在我的存储库类中处理它。
  • @Chad Richardson 我同意,您不必更改 EF 生成的类。正确的解决方案是在元数据类中添加以下内容:[MetadataType(typeof(CompanyMetadata))]public partial class Company{ }
  • 我编辑了我的答案,以展示比更改自动生成的文件更好的方法。
【解决方案2】:

我发现我需要在我的 Repository 类中使​​用 GetNew() 方法来处理这个问题,该方法将填充该类的新实例的默认值。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-17
    • 2015-02-22
    相关资源
    最近更新 更多