您的位置:首页 > 数据库

NopCommerce 数据库初始化

2015-07-29 19:26 344 查看
NopCommerce数据库初始化比较复杂,我简化了,只初始化创建一张表,不多说,直接上代码:

//数据实体

/// <summary>
/// Represents an affiliate
/// </summary>
public partial class Affiliate
{
/// <summary>
/// Gets or sets the address identifier
/// </summary>
public int AddressId { get; set; }

/// <summary>
/// Gets or sets the admin comment
/// </summary>
public string AdminComment { get; set; }

/// <summary>
/// Gets or sets the friendly name for generated affiliate URL (by default affiliate ID is used)
/// </summary>
public string FriendlyUrlName { get; set; }

/// <summary>
/// Gets or sets a value indicating whether the entity has been deleted
/// </summary>
public bool Deleted { get; set; }

/// <summary>
/// Gets or sets a value indicating whether the entity is active
/// </summary>
public bool Active { get; set; }

}

public partial class AffiliateMap : NopEntityTypeConfiguration<Affiliate>
{
public AffiliateMap()
{
this.ToTable("Affiliate");//表名
this.HasKey(a => a.AddressId);//设置主键
}
}


public abstract class NopEntityTypeConfiguration<T> : EntityTypeConfiguration<T> where T : class
{
protected NopEntityTypeConfiguration()
{
PostInitialize();
}

/// <summary>
/// Developers can override this method in custom partial classes
/// in order to add some custom initialization code to constructors
/// </summary>
protected virtual void PostInitialize()
{

}
}


//创建上下文 通过反射获取要加载的类

/// <summary>
/// Object context
/// </summary>
public class NopObjectContext : DbContext
{

public DbSet<Affiliate> Affiliates { get; set; }

/// <summary>
///
/// </summary>
/// <param name="modelBuilder"></param>
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
//dynamically load all configuration
//System.Type configType = typeof(LanguageMap);   //any of your configuration classes here
//var typesToRegister = Assembly.GetAssembly(configType).GetTypes()

var typesToRegister = Assembly.GetExecutingAssembly().GetTypes()
.Where(type => !String.IsNullOrEmpty(type.Namespace))
.Where(type => type.BaseType != null && type.BaseType.IsGenericType &&
type.BaseType.GetGenericTypeDefinition() == typeof(NopEntityTypeConfiguration<>));
foreach (var type in typesToRegister)
{
dynamic configurationInstance = Activator.CreateInstance(type);
modelBuilder.Configurations.Add(configurationInstance);//获取此 DbModelBuilder 的 ConfigurationRegistrar。 注册器允许使用此生成器来注册派生的实体和复杂类型配置。
}
//...or do it manually below. For example,
//modelBuilder.Configurations.Add(new LanguageMap());

base.OnModelCreating(modelBuilder);
}
}


//测试

Database.SetInitializer(new DropCreateDatabaseAlways<NopObjectContext>());//创建新的数据库
using (NopObjectContext ctx = new NopObjectContext())
{
ctx.Database.Initialize(force: true);
}


这里都结束了,当然Nop用的要复杂的多,这里都简单介绍哈
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: