【问题标题】:Model property initialization模型属性初始化
【发布时间】:2013-12-16 15:19:43
【问题描述】:

我有这个模型类“UserProfile”,它是 Membership 的原始 UserProfile 类,添加了一些属性和方法。

[Table("UserProfile")]
public class UserProfile
{

   public UserProfile()
   {
       this.DictionaryFrom = "eng";
       this.DictionaryTo = "hun";
       this.trainingType = "normal";
   }


    [Key]
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    public int UserId { get; set; }
    public string UserName { get; set; }
    public string DictionaryFrom { get; set; }
    public string DictionaryTo { get; set; }
    public string trainingType { get; set; }

    public virtual ICollection<ForeignExpression> learnedexpressions { get ; set ; }
}

我的问题是,在注册新用户时,构造函数中的三个字段没有获得分配给它们的值(因此,数据库中每个字段都有一个 NULL)。 用户可以通过从列表中选择值来设置它们,但我想为所有这些设置一个默认值。我做错了什么?

【问题讨论】:

  • 您是否在保存之前不小心取消了其他地方的值?
  • @ohiodoug 我不这么认为,构造函数中的代码似乎在创建新用户的过程中运行,但对数据库没有任何影响。
  • 您是否在表单中包含这些字段并允许用户发布未填写的字段?
  • @dombenoit 不,我使用的是默认的会员注册页面(/Account/Register),没有任何修改
  • 你能展示你的视图和控制器的GET/POST方法吗?

标签: c# entity-framework asp.net-mvc-4 code-first


【解决方案1】:

不是 C# 爱好者,我会做这样的事情......可能有一种“更好”的方法。

private string myValue = "default value";

public string MyValue {
    get { return myValue; }
    set {
        if (null != value) { myValue = value; }
    }
}

【讨论】:

    猜你喜欢
    • 2017-02-21
    • 1970-01-01
    • 1970-01-01
    • 2018-11-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-17
    相关资源
    最近更新 更多