Entity Framework basics-Article 6 (Code First), entityframework
If you don't need to talk about it, create a project directly below:
1. Create a console application
Public class UserInfo
{
public UserInfo() { OrderInfo = new HashSet<OrderInfo>(); }
[Key]
Public int UserID {get; set;} // primary key
Public string UserName {get; set;} public virtual ICollection <OrderInfo> OrderInfo {get; set;} // navigation attribute}
public class OrderInfo { [Key]
public int ID { get; set; } public string OrderContent { get; set; } public virtual UserInfo UserInfo { get; set; } }
Add Key reference:
Public class CodeFirstDbContext: DbContext {public CodeFirstDbContext (): base ("name = ModelFirstKey") {} protected override void OnModelCreating (DbModelBuilder modelBuilder) {modelBuilder. conventions. remove <PluralizingTableNameConvention> (); // Remove the complex table name s} public DbSet <UserInfo> UserInfo {get; set;} public DbSet <OrderInfo> OrderInfo {get; set ;}}
5. Configure App. config
<connectionStrings> <add name="ModelFirstKey" connectionString="server=.;uid=sa;pwd=123;database=CodeFirstDemoDB;" providerName="System.Data.SqlClient"/> </connectionStrings>
6. add data
static void Main(string[] args){
using(CodeFirstDbContext dbContext = new CodeFirstDbContext())
{ dbContext.Database.CreateIfNotExists(); UserInfo userInfo = new UserInfo(); userInfo.UserName = "xiaoyang"; dbContext.UserInfo.Add(userInfo); dbContext.SaveChanges(); Console.ReadKey();
}}
Run to automatically generate databases and tables: