2012-04-06 65 views
1

我正在为用户创建一个模型,并且希望将该属性连接设置为Now()。这里是我的代码:将当前日期分配给MVC中的某个属性

[DefaultValue(DateTime.Now)] 
public DateTime joined {get; set;} 

我得到错误:

An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type.

我在做什么错?什么是做我想做的最好的方式?

回答

7

DateTime.Now不是一个常量,但那是在运行时计算的属性,这就是为什么你不能做你所建议。

你可以做你正在使用或者提出什么:

public class MyClass { 
    public DateTime joined { get; set; } 
    public MyClass() { 
    joined = DateTime.Now; 
    } 
} 

或者:

public class MyClass { 
    private DateTime _joined = DateTime.Now; 
    public DateTime joined { get { return _joined; } set { _joined = value; } } 
} 
1

你可以在你的模型类试试这个:

private DateTime _joined = DateTime.Now; 
public DateTime Joined 
{ 
    get { return _joined; } 
    set { _joined = value; } 
} 
1

您不能设置表达式为默认值属性。由于数据协议不是运行时属性。你应该这样

private DateTime _joined = DateTime.Now; 
public DateTime Joined 
{ 
    get { 
     return _joined; 
    } 
    set { 
     _joined = value; 
    } 
} 
1

你可以做到这一点像什么其他建议设置默认值,但另一种选择是将其设置成你的操作方法,从视图模型域的映射后,只是在添加它之前到数据库(如果这是你需要做什么):

[HttpPost] 
public ActionResult Create(YourViewModel viewModel) 
{ 
    // Check if view model is not null and handle it if it is null 

    // Do mapping from view model to domain model 
    User user = ... // Mapping 
    user.DateJoined = DateTime.Now; 

    // Do whatever else you need to do 
} 

您的用户domail型号:

public class User 
{ 
    // Other properties here 

    public DateTime DateJoined { get; set; } 
} 

我个人已经在行动方法对其进行设置,因为日期和时间会更接近用户实际添加到数据库的时间(假设这是您想要做的)。假设您在12:00创建用户对象,那么这将是您将用户添加到数据库的时间,但如果您只在12:30点击提交按钮,该怎么办?我宁愿12点30分而不是12点。

+0

我同意这是更好的解决方案,用户可以打开查看并设置日期时间,但如果他们根据您的缓存策略长时间保留该视图,则可能会不一致。我个人使用一个基类DTO,所有DTO派生自包含CreatedBy,CreatedDate,LastUpdatedBy,LastUpdatedDate属性的基类DTO。这些会在被保存到数据库之前设置 – 2012-04-06 18:36:38

相关问题