Winform--數據庫鏈接(EF CodeFirst)


寫web程序寫到一定的瓶頸了,就想換種技術深入的寫寫。看能不能提高自己。選擇了winform 和python。這兩個的學習筆記都會記錄分享。

不管winform還是web還是WebService還是WebApi都得與數據庫打交道。現在關系性數據庫應用越來越廣泛。這里就選擇了EF。有的人說EF太"重",不是輕量級的。

這里想說很多時候是自己水平不行,不是EF不行。當然EF不能解決所有的數據存儲查詢問題,但是它絕對能解決大部分問題。由於是學習,不指定需求。所以就使用CodeFirst設計模式。

由於水平有限,有時候理解不到位。請大家多多指正。

     1:  新建一個類庫,取名字叫EFSql 。NuGet EF 6.0 以上的版本。(^_^5.0的版本我的EF命令通不過)

     2:新建一個類。取名為:SqlDbContext 內容如下:

          

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

namespace EFSql
{
    public class SqlDbContext : DbContext
    {
        public SqlDbContext() : base("DefaultConnection") { }

        public DbSet<Model.UserInfo> UserInfos { get; set; }

        public DbSet<Model.TeamInfo> TeamInfos { get; set; }

        public DbSet<Model.TableInfo> TableInfos { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
        }
    }
}

  其中  modelBuilder.Conventions.Remove<PluralizingTableNameConvention>(); 去除注冊變量的S。不然在數據庫用生成的表就會帶上S。構造函數中的"DefaultConnection" 是啟動項目中配置文件中的鏈接字符串。

      3:新建一個Model類庫。 引用 using System.ComponentModel.DataAnnotations 這個類庫。

        舉個類的例子如下:

        

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

namespace Model
{
    public class UserInfo
    {
        [Key]
        [Required]
        public string userCode { get; set; }
        [MaxLength(36)]
        [Required]
        public string userName { get; set; }
        [MaxLength(8)]
        [Required]
        public string userPassword { get; set; }

        public DateTime? lastLoginTime { get; set; }
    }
}

  必須指定Key。非必選字段類型添加上?。字符串類型必須指定長度。就如上面的例子userCode 沒有指定長度。在數據庫種生成的字段長度為128位。實際36位就可以了。

      4: 在Visual Studio 中 選擇 "工具" ——> "NuGet程序管理器"——>"程序包管理控制台".會出現命令界面:

            輸入:enable-migrations  add-migration  

      5: 如果新建了類,或者修改了原有類的結果使用 update-database 。更多的命令參考官網。

      這樣就搭建完了與數據鏈接的整體。  

          


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM