连接EF并插入数据
配置文件:
<?xml version="1.0" encoding="utf-8"?> <configuration> <configSections> <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" /> </configSections> <startup> <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" /> </startup> <connectionStrings> <add name="AOC" connectionString="Data Source=;Initial Catalog=;Persist Security Info=True;User ID=;Password=" providerName="System.Data.SqlClient" /> </connectionStrings> <entityFramework> <providers> <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" /> </providers> </entityFramework> </configuration>
在Modles中创建DataContext.cs
using System.Data.Entity; using System.Data.Entity.ModelConfiguration.Conventions; namespace Modles { public class DataContext : DbContext { public DataContext() : base("AOC") { }//指定连接字符串 //系统表 public DbSet<PreTest> PreTest { get; set; } protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Conventions.Remove<PluralizingTableNameConvention>(); // 移除EF的表名公约 //modelBuilder.Conventions.Remove<OneToOneConstraintIntroductionConvention>(); //modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>(); //modelBuilder.Conventions.Remove<ManyToManyCascadeDeleteConvention>(); //var instance = System.Data.Entity.SqlServer.SqlProviderServices.Instance; } public void FixEfProviderServicesProblem() { //The Entity Framework provider type 'System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer' //for the 'System.Data.SqlClient' ADO.NET provider could not be loaded. //Make sure the provider assembly is available to the running application. //See http://go.microsoft.com/fwlink/?LinkId=260882 for more information. var instance = System.Data.Entity.SqlServer.SqlProviderServices.Instance; } } }
创建数据库对应实体类
[Table("SingleUse_COB_PreTest")] public class PreTest { [Key] public int items { get; set; } public string cdata { get; set; } public string Item { get; set; } public string LotNumber { get; set; } public string CH1_2p50mA { get; set; } }
插入数据:
public void COBWriteDB(List<PreTest> Data) { //IList<COB_BurnInPreTest> JsonList = JsonToModels(Data); using (var db = new DataContext()) { db.PreTest.AddRange(Data); db.SaveChanges(); } }