And*_*ndy 46 .net entity-framework entity-framework-4 ef-code-first
在Entity Framework Code First方法中,如何在POCO的EntityConfiguration类中为属性设置默认值?
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
public DateTime CreatedOn { get; set; }
}
public class PersonConfiguration : EntityConfiguration<Person>
{
public PersonConfiguration()
{
Property(p => p.Id).IsIdentity();
Property(p => p.Name).HasMaxLength(100);
//set default value for CreatedOn ?
}
}
Run Code Online (Sandbox Code Playgroud)
Chr*_*cey 24
随着Entity Framework 4.3的发布,您可以通过迁移实现此目的.
所以使用你的例子它会是这样的:
public partial class AddPersonClass : DbMigration
{
public override void Up()
{
CreateTable(
"People",
c => new
{
Id = c.Int(nullable: false, identity: true),
Name = c.String(maxLength: 100),
CreatedOn = c.DateTime(nullable: false, defaultValue: DateTime.UtcNow)
})
.PrimaryKey(t => t.Id);
}
public overide void Down()
{
// Commands for when Migration is brought down
}
}
Run Code Online (Sandbox Code Playgroud)
Gav*_*tes 15
您可以通过类的构造函数设置默认值.这是我在当前项目中使用MVC3和Entity Framework 4.1的类:
namespace MyProj.Models
{
using System;
using System.Collections.Generic;
public partial class Task
{
public Task()
{
this.HoursEstimated = 0;
this.HoursUsed = 0;
this.Status = "To Start";
}
public int ID { get; set; }
public string Description { get; set; }
public int AssignedUserID { get; set; }
public int JobID { get; set; }
public Nullable<decimal> HoursEstimated { get; set; }
public Nullable<decimal> HoursUsed { get; set; }
public Nullable<System.DateTime> DateStart { get; set; }
public Nullable<System.DateTime> DateDue { get; set; }
public string Status { get; set; }
public virtual Job Job { get; set; }
public virtual User AssignedUser { get; set; }
}
}
Run Code Online (Sandbox Code Playgroud)
我知道这个话题已经持续了一段时间,我走进了某种相同的问题.到目前为止,我无法找到一个解决方案,将整个事物放在一个地方,因此代码仍然可读.
在创建用户时,我希望通过对象本身设置一些字段private setters
,例如GUID和创建日期,而不是"污染"构造函数.
我的用户类:
public class User
{
public static User Create(Action<User> init)
{
var user = new User();
user.Guid = Guid.NewGuid();
user.Since = DateTime.Now;
init(user);
return user;
}
public int UserID { get; set; }
public virtual ICollection<Role> Roles { get; set; }
public virtual ICollection<Widget> Widgets { get; set; }
[StringLength(50), Required]
public string Name { get; set; }
[EmailAddress, Required]
public string Email { get; set; }
[StringLength(255), Required]
public string Password { get; set; }
[StringLength(16), Required]
public string Salt { get; set; }
public DateTime Since { get; private set; }
public Guid Guid { get; private set; }
}
Run Code Online (Sandbox Code Playgroud)
来电代码:
context.Users.Add(User.Create(c=>
{
c.Name = "Name";
c.Email = "some@one.com";
c.Salt = salt;
c.Password = "mypass";
c.Roles = new List<Role> { adminRole, userRole };
}));
Run Code Online (Sandbox Code Playgroud)
不幸的是你不能。http://social.msdn.microsoft.com/Forums/en/adonetefx/thread/a091ccd6-0ba8-4d4f-8f5e-aafabeb258e4
归档时间: |
|
查看次数: |
38062 次 |
最近记录: |