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

创建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表中添加两条记录

这里写图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值