您的位置:首页 > 编程语言 > ASP

ASP.NET ZERO 学习 —— (10) 应用开发Demo之创建实体对象

2017-03-06 16:18 260 查看

创建Person实体

我们在.Core项目中定义实体。我们可以定义一个Person实体(和数据库中的PbPerson表映射)用来显示电话薄中的信息,在.Core项目中创建名为Entities的文件夹,并创建一个Person类,添加以下代码:

[Table("PbPersons")]
public class Person : FullAuditedEntity
{
public const int MaxNameLength = 32;
public const int MaxSurnameLength = 32;
public const int MaxEmailAddressLength = 255;

[Required]
[MaxLength(MaxNameLength)]
public virtual string Name { get; set; }

[Required]
[MaxLength(MaxSurnameLength)]
public virtual string Surname { get; set; }

[MaxLength(MaxEmailAddressLength)]
public virtual string EmailAddress { get; set; }
}


Person的主键默认为int型。基类FullAuditedEntity包括创建,修改,删除的审计属性,它也是软删除的。当我们删除一个Person时,他并不是从数据库中进行物理删除,而只是把其标记为deleted。我们创建了很多MaxLength的常量,这是一个很好的做法,因为后面我们将用到相同的值。

我们在.EntityFramework项目下的AbpZeroTemplateDbContext类里面为Person实体添加一个DbSet属性。

public class AbpZeroTemplateDbContext : AbpZeroDbContext<Tenant, Role, User>
{
/* Define an IDbSet for each entity of the application */

public virtual IDbSet<BinaryObject> BinaryObjects { get; set; }

public virtual IDbSet<Friendship> Friendships { get; set; }

public virtual IDbSet<ChatMessage> ChatMessages { get; set; }

public virtual IDbSet<Person> Persons { get; set; }

public AbpZeroTemplateDbContext()
: base("Default")
{

}
}


数据迁移

我们使用EntityFramewoke 的 Code-First 来做数据库架构的迁移。当我们添加了Person 实体后,我们都数据模型已经被改变。所以,我们需要创建一个新的migration去数据库中创建表。

打开程序包管理器控制台,选择.EntityFramewoke作为默认项目,输入下面的命令



运行这个命令后会添加一个叫Added_Persons_Table的数据迁移类,如下所示:

public partial class Added_Persons_Table : DbMigration
{
public override void Up()
{
CreateTable(
"dbo.PbPersons",
c => new
{
Id = c.Int(nullable: false, identity: true),
Name = c.String(nullable: false, maxLength: 32),
Surname = c.String(nullable: false, maxLength: 32),
EmailAddress = c.String(maxLength: 255),
IsDeleted = c.Boolean(nullable: false),
DeleterUserId = c.Long(),
DeletionTime = c.DateTime(),
LastModificationTime = c.DateTime(),
LastModifierUserId = c.Long(),
CreationTime = c.DateTime(nullable: false),
CreatorUserId = c.Long(),
},
annotations: new Dictionary<string, object>
{
{ "DynamicFilter_Person_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
})
.PrimaryKey(t => t.Id);

}

public override void Down()
{
DropTable("dbo.PbPersons",
removedAnnotations: new Dictionary<string, object>
{
{ "DynamicFilter_Person_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
});
}
}


我们不需要了解太多关于该文件的格式和规则。但是,建议对迁移有一个基本的了解。在程序包管理器控制台中输入“Update-Database”命令来执行迁移。更新后,我们可以在数据库中看见新增了PbPersons表。



但是这个表是空的。我们可以使用EF中的Seed方法向数据库中初始化一些数据。在ASP.NET Zero里,有一些类可以为用户和设置添加初始化数据。



所以,我们可以添加一个InitialPeopleCreator类来填充一些Person的数据,如下图所示:

public class InitialPeopleCreator
{
private readonly AbpZeroTemplateDbContext _Context;

public InitialPeopleCreator(AbpZeroTemplateDbContext context)
{
this._Context = context;
}

public void Create()
{
var alistair = this._Context.Persons.FirstOrDefault(p => p.EmailAddress == "alistair.chow@ali.com");

if(alistair == null)
{
this._Context.Persons.Add(
new Entities.Person
{
Name = "Alistair",
Surname = "Chow",
EmailAddress = "alistair.chow@ali.com"
});
}

var tencent = this._Context.Persons.FirstOrDefault(p => p.EmailAddress == "tencent.cloud@ali.com");
if (tencent == null)
{
this._Context.Persons.Add(
new Entities.Person
{
Name = "Tencent",
Surname = "Cloud",
EmailAddress = "tencent.cloud@ali.com"
});
}
}
}


再在EntityFramework项目的Migrations文件夹下的Configuration类中,调用InitialPeopleCreator

protected override void Seed(EntityFramework.AbpZeroTemplateDbContext context)
{
context.DisableAllFilters();

context.EntityChangeEventHelper = NullEntityChangeEventHelper.Instance;
context.EventBus = NullEventBus.Instance;

if (Tenant == null)
{
//Host seed
new InitialHostDbBuilder(context).Create();

//Default tenant seed (in host database).
new DefaultTenantBuilder(context).Create();
new TenantRoleAndUserBuilder(context, 1).Create();
new InitialPeopleCreator(context).Create();
}
else
{
//You can add seed for tenant databases using Tenant property...
}

context.SaveChanges();
}


再次执行Update-Database命令。命令会执行Seed想PbPersons表中添加两条记录

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: