使用ADO.NET实体数据模型创建表

132 阅读1分钟
using System;
using System.Collections.Generic;

using System.ComponentModel.DataAnnotations;

using System.ComponentModel.DataAnnotations.Schema;

using System.Data.Entity;

using System.Linq;

namespace MVCjichu.Models
{
    public class Model1 : DbContext
    {
        public Model1()
            : base("name=Model1")
        {
        }

    //引用下面的StuInfo的表
    public virtual DbSet<stuInfo> StuInfo { get; set; }

    public virtual DbSet<Course> Course { get; set; }

    public virtual DbSet<Score> Score { get; set; }
    //为您要在模型中包含的每种实体类型都添加 DbSet。有关配置和使用 Code First  模型
    //的详细信息,请参阅 http://go.microsoft.com/fwlink/?LinkId=390109。

    // public virtual DbSet<MyEntity> MyEntities { get; set; }
}
public class stuInfo
{
    /// <summary>
    /// 外键
    /// 
    /// </summary>
    //public virtual stuInfo()
    //{
    //    return Score = new HashSet<Score>();
    //}
    /*
     主键(三种方法):id
          类名Id  stuInfoId
          [key]
     */
    /*
     null
         public DateTime? Birthday { get; set; }
        可不可以存储null
    默认值
        public DateTime Birthday { get; set; }=null
     */
    public int Id { get; set; }
    [Display(Name="姓名")]
    public string Name { get; set; }

    [Display(Name = "日期")]
    public DateTime Birthday { get; set; }

    public virtual ICollection<Score> Scores { get; set; } = new HashSet<Score>();
}
public class Course
{
    public int Id { get; set; }
    public string Name { get; set; }

    public virtual ICollection<Score> Score { get; set; } = new HashSet<Score>();
}
public class Score {
    public int Id { get; set; }

    public int Value { get; set; }

    public int stuInfoId { get; set; }
    
    [ForeignKey("stuInfoId")]
    public stuInfo stuInfo { get; set; }

    public int CourseId { get; set; }

    [ForeignKey("CourseId")]
    public Course Course { get; set; }
}
}