最近研究深入研究codefirst 研究成果,但是我发现我不能进行团队合作,比如我写的codefirst数据库和我同事的不能很好的整合(我是写前端的,她是写数据库的,我这样就抢饭碗了)。所以决定先把学成的写下备用。
该方法的使用过程如下
1.创建一个console程序或者MVC4空程序。
2.添加entityframework
Tools –> Library Package Manager –> Package Manager Console 然后键入Install-Package EntityFramework 获取最新entityframework(mvc支持到entityframework 5所以 使用Install-Package EntityFramework -version 5.0 添加,版本为4.4.0.0)
下面为mvc4自动生成的连接字符串
<connectionStrings>
<add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=aspnet-PPP-20150415155322;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnet-PPP-20150415155322.mdf" providerName="System.Data.SqlClient" />
</connectionStrings>
3添加codefirst代码
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity;
namespace PPP.Models
{
public class MarkContext : DbContext
{
public MarkContext()
: base("DefaultConnection")//连接字符串,如果是mvc则在web.config里定义。
{
Database.SetInitializer<MarkContext>(new DropCreateDatabaseAlways<MarkContext>());//自定义初始化方式(总是新建数据库)
// Database.SetInitializer<MarkContext>(new CreateDatabaseIfNotExistss<MarkContext>());//默认初始化方式(没有数据库的时候新建)
}
public DbSet<Mark> Marks { get; set; }//
}
[Table("Mark")]
public class Mark
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int id { get; set; }
public string name { get; set; }
public string url{ get; set; }
public string img { get; set; }
public double lat { get; set; }//维度
public double lng { get; set; }//经度
public int percent{ get; set; }
public string status { get; set; }
public DateTime time { get; set; }
// public virtual UserProfile belongsto { get; set; }
// public UserProfile belongsto { get; set; }
// [ForeignKey("UserProfile")]
public int belongsto { get; set; }
[ForeignKey("belongsto")]
public virtual UserProfile UserProfile { get; set; }
}
}
总的来说还没有完全弄明白什么是导航属性,导航属性不会出现在生成的数据库里,那么上面的 public virtual UserProfile UserProfile { get; set; }便是导航属性。在上面的model里
public int belongsto { get; set; }
[ForeignKey("belongsto")]
public virtual UserProfile UserProfile { get; set; }
//生成外键belongsto
这三个完成了外键约束的任务。使得数据库生成一个belongsto的外键,并指向UserProfile的key。
或者修改为下面的
[ForeignKey("UserProfile")]
public int belongsto { get; set; }
public virtual UserProfile UserProfile { get; set; }
//生成外键belongsto
还有其他的方法比如
public virtual UserProfile belongsto { get; set; }
//或者没有virtual(用于延迟)
public UserProfile belongsto { get; set; }
//那么生成外键belongsto_Userid (UserProfile的key)
4.激活迁移(migration)
键入Enable-Migrations 来激活迁移方案。自动创建Migrations 文件夹和两个文件The Configuration class,An InitialCreate migration
5.修改model。
6.添加迁移方案 键入 Add-Migration 迁移名 然后更新数据库 Update-Database 或Update-Database –Verbose(可以看到sql)
其他1.回滚到以前的迁移 Update-Database –TargetMigration: InitialDatabase其他2.使用SQLscript进行迁移Update−Database−script其他3.使用SQLscript定向迁移Update−Database−Script−SourceMigration: InitialDatabase -TargetMigration: AddPostAbstract