Entity Framework basics-Article 6 (Code First), entityframework

Source: Internet
Author: User
Tags connectionstrings

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:

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.