EF code first 自动创建数据库,创建表,配置实体类与表的映射

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity;
using System.Data.Entity.ModelConfiguration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp3
{
    class Program
    {
        static void Main(string[] args)
        {
            using (var context = new EntFraContext())
            {

//DBSet和context合作新增数据
                var name = "员工名称111";
                var blog = new Employee { Name = name };
                context.EmployeeSet.Add(blog);//经过调试和观察(刷新数据库列表)发现,创建数据库和表结构是在Add方法里面完成的。方法SaveChanges()只是针对数据的增删改。 

  context.SaveChanges();

 //DBSet和context合作更新
                //Employee e = context.EmployeeSet.Find(1);
                //e.Name = "HelenZhou"; 
                //context.SaveChanges();

//DBSet和Context合作删除数据
                //Employee e = context.EmployeeSet.Find(1);
                //context.EmployeeSet.Remove(e);
                删除多个,用下面这个方法
                context.EmployeeSet.RemoveRange(list);
                //context.SaveChanges();

                DBSET,非原生查询,查询单个实体
                //Employee e = context.EmployeeSet.Find(1);
                //Console.WriteLine(e.Name);
                DBSET查询实体集合或者(单个,里面带有集合)---查看文章:EF 加载数据的3种方式

                    #region 顺便提一下:DBSet支持原生查询
                //var EmployeeList =
                //    context.EmployeeSet.SqlQuery
                //    ("SELECT * FROM dbo.Employee").ToList();
                //foreach (var item in EmployeeList)
                //{
                //    var aa = item.Name;
                //}
                //                var EmployeeList =
                //                    context.EmployeeSet.SqlQuery
                //                    (@"SELECT * FROM dbo.Employee 
                //a
                //LEFT JOIN
                //dbo.Account b
                //on a.Id
                //= b.AccountId").ToList();
                //foreach (var item in EmployeeList)
                //{
                //    var aa = item.Name;
                //}    
                #endregion
             
            }
            Console.WriteLine("保存OK!");
            Console.Read();
        }
    }

    public class Employee
    {
        public int Id { get; set; }

        public string Name { get; set; }

        public virtual Account Account { get; set; }
    }
    public class Account
    {
        public int Id { get; set; }

        public string UserName { get; set; }

        public string Password { get; set; }

        public virtual Employee Employee { get; set; }
    }
    //配置实体类到表的映射
    public class EmployeeMap : EntityTypeConfiguration<Employee>
    {
        public EmployeeMap()
        {
            this.ToTable("Employee");
            this.HasKey(p => p.Id);
            this.Property(p => p.Id).IsRequired().HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
            this.Property(p => p.Name).IsRequired().HasMaxLength(63);
        }
    }

    //配置实体类到表的映射
    public class AccountMap : EntityTypeConfiguration<Account>
    {
        public AccountMap()
        {
            this.ToTable("Account");
            this.HasKey(p => p.Id);
            this.Property(p => p.Id).IsRequired().HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
            this.Property(p => p.UserName).IsRequired().HasMaxLength(63);
            this.Property(p => p.Password).IsRequired().HasMaxLength(63);

            this.HasRequired(m => m.Employee)
                .WithOptional(m => m.Account)
                .Map(m => m.MapKey("AccountId"))
                .WillCascadeOnDelete(true);
        }
    }


    public class EntFraContext : DbContext
    {
        public EntFraContext() : base("name=ConnectionString")
        {
            Database.SetInitializer(
                new CreateDatabaseIfNotExists
                <EntFraContext>());
        }
        public IDbSet<Account> AccountSet { get; set; }

        public IDbSet<Employee> EmployeeSet { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Configurations.Add(new AccountMap());
            modelBuilder.Configurations.Add(new EmployeeMap());
            base.OnModelCreating(modelBuilder);
        }
    }
}
 

app.config:

<connectionStrings>
        <add name="ConnectionString"
             connectionString="Data Source=MS-20170712GAIC\SQLEXPRESS;Initial Catalog=CodeFirst;Persist Security Info=True;User ID=sa;Password=helenzhou" 
             providerName="System.Data.SqlClient"  />
    </connectionStrings>

<entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
    <providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
  </entityFramework>

转载:https://www.cnblogs.com/lcblog/articles/4498909.html

 

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值