EntityFramework初入

//NuGet包管理,搜索引入 EntityFramework6 、Newtonsoft
//使用:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Data.Entity;
using System.Data.SqlClient;
using System.Configuration;
using Newtonsoft.Json;
namespace EF_Test
{
class Program
{
static void Main(string[] args)
{
try
{
TestContext testContext = new TestContext();
var personList = testContext.TestTables.AsNoTracking().ToList();
Console.WriteLine(JsonConvert.SerializeObject( personList));

//通过DBContext.Database,不需要创建对应Entity,可创建sqlconnection,sql语句返回DataTable
//DataTable dddd = SqlQueryForDataTatable(testContext.Database, "select * from TestTable");
//if (dddd.Rows.Count > 0)
//{
// Console.WriteLine(dddd.Rows[0]["AAAA"].ToString());
//}
//Console.WriteLine("END");
}
catch (Exception exc)
{
Console.WriteLine(exc.Message);
}
Console.Read();
}

public static DataTable SqlQueryForDataTatable(Database db,string sql)
{
SqlConnection conn = (SqlConnection)db.Connection;
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandText = sql;

SqlDataAdapter adapter = new SqlDataAdapter(cmd);
DataTable table = new DataTable();
adapter.Fill(table);

conn.Close();//连接需要关闭
conn.Dispose();
return table;
}
}

//直接借鉴网上代码
public class TestContext : DbContext
{
private static TestContext _instance;

public static TestContext Instance
{
get
{
if (_instance == null)
{
_instance = new TestContext();
}
return _instance;
}
}

private string _connectionString;

public string ConnectionString
{
get
{
if (string.IsNullOrWhiteSpace(_connectionString))
{
_connectionString = ConfigurationManager.ConnectionStrings["MyDbContext"].ConnectionString;
}
return _connectionString;
}
set
{
_connectionString = value;
}
}

public TestContext()
: base("MyDbContext")
{
//DBContext直接根据MyDbContext键值去config中读取对应的value并创建链接
}

public TestContext(string connectionString)
: base(connectionString)
{

}

/// <summary>
/// 定义的实体
/// </summary>
public DbSet<TestTable> TestTables { get; set; }

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
//表名映射
base.OnModelCreating(modelBuilder);
modelBuilder.Types().Configure(t =>
{
//获取类名
var tableName = t.ClrType.Name;
//将类名处理为指定规范表名
tableName = tableName.Replace("Entity", "");
t.ToTable(tableName);
});
}
}
//对应表已在数据库中创建
public class TestTable
{
public int id { get; set; }
public string AAAA { get; set; }
public string BBBB { get; set; }
}
}

 

posted on 2020-11-02 16:19  3SU  阅读(70)  评论(0编辑  收藏  举报