• 星空雅梦


        为了支持以设计为中心的开发流程,EF还更多地支持以代码为中心 (code-centric) ,我们称为代码优先的开发,代码优先的开发支持更加优美的开发流程,它允许你在不使用设计器或者定义一个 XML 映射文件的情况下进行开发。

      ·允许编写简单的模型对象POCO (plain old classes),而不需要基类。

      ·通过"约定优于配置",使得数据库持久层不需要任何的配置

      ·也可以覆盖"约定优于配置",通过流畅的 API 来完全定制持层的映射。

      Code First是基于Entity Framework的新的开发模式,原先只有Database First和Model First两种。Code First顾名思义,就是先用C#/VB.NET的类定义好你的领域模型,然后用这些类映射到现有的数据库或者产生新的数据库结构。Code First同样支持通过Data Annotations或fluent API进行定制化配置。

        下面我就来进行codeFirst的演示:

        先建立控制台程序:

        

       然后新建类:

       

       新建Customer,OrderInfo,以及 HotelDbContext类

      在编码前进行相应的引用,然后进行类的编码:

      

      

      Customer类:


    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;

    namespace CodeFirst1
    {
    public class Customer
    {
    public int Id { get; set; }

    public string CusName { get; set; }

    public virtual ICollection<OrderInfo> order { get; set; }


    }
    }
       

       OrderInfo类:


    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.ComponentModel.DataAnnotations;

    namespace CodeFirst1
    {
    public class OrderInfo
    {
    [Key]
    public int Id { get; set; }

    public string content { get; set; }
    /// <summary>
    /// 外键
    /// </summary>
    public int customerId { get; set; }

    public Customer Customer { get; set; }
    }
    }

          这里要注意Key的主键的问题
      HotelDbContxt类的编写:


    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Data.Entity;

    namespace CodeFirst1
    {
    public class HotelDbContext :DbContext
    {
    public HotelDbContext()
    : base("name=ConnCodeFirst")
    {
    }
    public DbSet<Customer> Customer { get; set; }

    public DbSet<OrderInfo> OrderInfo { get; set; }

    }
    }

         编写成功后加上一个配置文件用来连接数据库:


      配置文件的编写如下:


    <?xml version="1.0" encoding="utf-8" ?>
    <configuration>
    <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.1" />
    </startup>
    <connectionStrings>
    <add name="ConnCodeFirst" connectionString="server=192.168.24.233;uid=sa;pwd=123456;database=CodeFirstDB"
    providerName="System.Data.SqlClient" />
    </connectionStrings>
    </configuration>


         最后运行程序:


      

      数据库展示如下:

       
    ---------------------
    作者:徐志鹏
    来源:CSDN
    原文:https://blog.csdn.net/u010158267/article/details/44100113
    版权声明:本文为博主原创文章,转载请附上博文链接!

  • 相关阅读:
    报数游戏
    Dynamics CRM 2013 初体验(2):UI
    Lucene.net常见功能实现知识汇总
    hdu 1853 最小费用流好题 环的问题
    MessagerService总结
    [置顶] Android EditText/TextView使用SpannableString显示复合文本
    MySQL Dll语句
    JavaScript表单验证
    intellij—idea14 注冊机
    OL记载Arcgis Server切片
  • 原文地址:https://www.cnblogs.com/LiZhongZhongY/p/10791528.html
Copyright © 2020-2023  润新知