CSharp: donet 6 or 7 Migrations with Entity Framework Core 6 or 7

 初始化创建表和数据

    /// <summary>
    /// 
    ///Entity
    /// </summary>
    public class Product
    {

        public Product() { }    

        public int Id { get; set; }
        public string Name { get; set; }
        public int Quantity { get; set; }
        public float Price { get; set; }
    }

    /// <summary>
    /// Entity
    /// geovindu, Geovin Du
    /// </summary>
    public class Customer
    {

        public Customer() {

    
        }
        public int Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }

    /// <summary>
    /// 
    /// </summary>
    public class ECommerceDbContext : DbContext
    {
        public DbSet<Product> Products { get; set; }
        public DbSet<Customer> Customers { get; set; }
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            optionsBuilder.UseSqlServer("Server=DESKTOP-NQK85G5\\GEOVIN2008;Database=geovinduCoreDBA;User Id=sa;Password=geovindu;");
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="modelBuilder"></param>
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Product>();
            modelBuilder.Entity<Customer>();
            base.OnModelCreating(modelBuilder);
        }
    }


    /// <summary>
    /// 初始化创建表格
    /// </summary>
    [DbContext(typeof(ECommerceDbContext))]
    partial class ECommerceDbContextModelSnapshot : ModelSnapshot
    {

        /// <summary>
        /// 
        /// </summary>
        /// <param name="modelBuilder"></param>
        protected override void BuildModel(ModelBuilder modelBuilder)
        {
#pragma warning disable 612, 618
            //ProductVersion
            modelBuilder
                .HasAnnotation("ProductVersion", "6.0.6")
                .HasAnnotation("Relational:MaxIdentifierLength", 128);

            SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder, 1L, 1);
            //Customer
            modelBuilder.Entity("Customer", b =>
                {
                    b.Property<int>("Id")
                        .ValueGeneratedOnAdd()
                        .HasColumnType("int");

                    SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"), 1L, 1);

                    b.Property<string>("FirstName")
                        .IsRequired()
                        .HasColumnType("nvarchar(max)");

                    b.Property<string>("LastName")
                        .IsRequired()
                        .HasColumnType("nvarchar(max)");

                    b.HasKey("Id");

                    b.ToTable("Customers");
                });
            //Product
            modelBuilder.Entity("Product", b =>
                {
                    b.Property<int>("Id")
                        .ValueGeneratedOnAdd()
                        .HasColumnType("int");

                    SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"), 1L, 1);

                    b.Property<string>("Name")
                        .IsRequired()
                        .HasColumnType("nvarchar(max)");

                    b.Property<float>("Price")
                        .HasColumnType("real");

                    b.Property<int>("Quantity")
                        .HasColumnType("int");

                    b.HasKey("Id");

                    b.ToTable("Products");
                });
#pragma warning restore 612, 618
        }
    }

  

调用:

//初始化表格至数据库
ECommerceDbContext context = new();
await context.Database.MigrateAsync();

//
context = new ECommerceDbContext();
List<Customer> customers = new List<Customer>();
//添加
Customer customer=new Customer();
customer.FirstName= "涂";
customer.LastName = "聚文";
customers.Add(customer);
customer = new Customer();
customer.FirstName = "Du";
customer.LastName = "geovind";
customers.Add(customer);
context.Customers.AddRange(customers);
int k=context.SaveChanges();
if (k > 0)
{
    Console.WriteLine("ok");
}
//查询
var custer=context.Customers.FirstOrDefault();
Console.WriteLine(custer.FirstName+","+custer.LastName);

  

输出:

 

 

 

 appsettings.json:

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*",
  "Persistence": {
    "Provider": "MSSQL"
  },
  "ConnectionStrings": {
    "GeovinDuDbContext": "Data Source=DESKTOP-NQK85G5\\GEOVIN2008;Initial Catalog=EntityFramework6;Integrated Security=SSPI;"
  }

}

  

using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using DuEntity;



namespace DuUtilitieDB
{

    /// <summary>
    /// geovindu
    /// </summary>
    public class DuDbContext : DbContext
    {

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

        public DbSet<DuCustomer> DuCustomer { get; set; }
      
        public DbSet<Student> Students { get; set; }
        public DbSet<Customer> Customers { get; set; }
        public DbSet<Order> Orders { get; set; }
        public DbSet<Category> Categories { get; set; }
        public DbSet<Product> Products { get; set; }
      


        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {

            //读取配置文件
            var config = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory()) //Environment.CurrentDirectory
                .AddJsonFile("appsettings.json")
                .AddInMemoryCollection()
                .Build();
            var connStr = config["ConnectionStrings:GeovinDuDbContext"];


            // optionsBuilder.UseSqlServer("Server=DESKTOP-NQK85G5\\GEOVIN2008;Database=geovindu;User Id=sa;Password=geovindu;");
            optionsBuilder.UseSqlServer(connStr);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="modelBuilder"></param>
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {

            modelBuilder.Entity<DuProduct>();
            modelBuilder.Entity<DuCustomer>();

            //modelBuilder.Entity<Student>();
            //modelBuilder.Entity<Product>();
            //modelBuilder.Entity<Category>();
            //modelBuilder.Entity<Customer>();


            base.OnModelCreating(modelBuilder);


        }
    }
}

  

        /// <summary>
        /// 存储过程输出参数
        /// EF Core 7
        /// </summary>
        /// <param name="category">输入</param>
        /// <param name="ategoryID">输出参数</param>
        /// <returns></returns>
        public int AddOutProc(Category category,out int categoryID)
        {
            int addok = 0;
      
            try
            {
                
                using (var context = new DuDbContext())
                {
                    addok = 0;

                    var parameter = new SqlParameter[]
                   {

                        new SqlParameter("@CategoryName",SqlDbType.NVarChar,200),
                        new SqlParameter("@CategoryId",SqlDbType.Int),

                      // ParameterName = "@CategoryId",
                       // SqlDbType = System.Data.SqlDbType.Int,
                      // Direction = System.Data.ParameterDirection.Output
                   };
                parameter[0].Value = category.CategoryName;
                 parameter[1].Direction = ParameterDirection.Output;                 

                 // addok = context.Database.ExecuteSqlRaw("dbo.proc_Insert_CategoriesOutput @CategoryName, @CategoryId OUTPUT", parameter);

                    addok = context.Database.ExecuteSqlRawAsync("dbo.proc_Insert_CategoriesOutput @CategoryName, @CategoryId OUTPUT",parameter).Result;

                    categoryID = (int)parameter[1].Value;
                    //context.Database.ExecuteSqlAsync($"UpdateStudentMark @Id={id}, @Mark={mark}");
                   
                }
            }
            catch (Exception ex)
            {
                categoryID = 0;
                ex.Message.ToString();
            }
            return addok;
        }

  

 

posted @ 2023-02-04 12:24  ®Geovin Du Dream Park™  阅读(46)  评论(0)    收藏  举报