您的位置:首页 > 数据库

EF中执行原生sql与使用Local获取本地数据

2015-07-22 21:38 585 查看
使用DbSet的Local属性可以访问当前context中被追踪且没有被标记为删除的实体(内存中的数据)

using (var context = new BloggingContext())
{
// Load some entities into the context
context.Blogs.Load();
context.Authors.Load();
context.Readers.Load();

// Make some changes
context.Blogs.Find(1).Title = "The New ADO.NET Blog";
context.Blogs.Remove(context.Blogs.Find(2));
context.Authors.Add(new Author { Name = "Jane Doe" });
context.Readers.Find(1).Username = "johndoe1987";

// Look at the state of all entities in the context
Console.WriteLine("All tracked entities: ");
foreach (var entry in context.ChangeTracker.Entries())
{
Console.WriteLine(
"Found entity of type {0} with state {1}",
ObjectContext.GetObjectType(entry.Entity.GetType()).Name,
entry.State);
}

// Find modified entities of any type
Console.WriteLine("\nAll modified entities: ");
foreach (var entry in context.ChangeTracker.Entries()
.Where(e => e.State == EntityState.Modified))
{
Console.WriteLine(
"Found entity of type {0} with state {1}",
ObjectContext.GetObjectType(entry.Entity.GetType()).Name,
entry.State);
}

// Get some information about just the tracked blogs
Console.WriteLine("\nTracked blogs: ");
foreach (var entry in context.ChangeTracker.Entries<Blog>())
{
Console.WriteLine(
"Found Blog {0}: {1} with original Name {2}",
entry.Entity.BlogId,
entry.Entity.Name,
entry.Property(p => p.Name).OriginalValue);
}

// Find all people (author or reader)
Console.WriteLine("\nPeople: ");
//返回所有实现IPerson接口的类的Name属性值
foreach (var entry in context.ChangeTracker.Entries<IPerson>())
{
Console.WriteLine("Found Person {0}", entry.Entity.Name);
}
}

public class Author : IPerson
{
public int AuthorId { get; set; }
public string Name { get; set; }
public string Biography { get; set; }
}

public class Reader : IPerson
{
public int ReaderId { get; set; }
public string Name { get; set; }
public string Username { get; set; }
}

public interface IPerson
{
string Name { get; }
}


View Code

EF中执行原生的sql语句

1.在指定实体上进行查询

using (var context = new BloggingContext())
{
var blogs = context.Blogs.SqlQuery("SELECT * FROM dbo.Blogs").ToList();
}


2.执行存储过程

using (var context = new BloggingContext())
{
var blogs = context.Blogs.SqlQuery("dbo.GetBlogs").ToList();
}

//带参数的存储过程
using (var context = new BloggingContext())
{
var blogId = 1;

var blogs = context.Blogs.SqlQuery("dbo.GetBlogById @p0", blogId).Single();
}


3.执行sql命令

using (var context = new BloggingContext())
{
var blogNames = context.Database.SqlQuery<string>(
"SELECT Name FROM dbo.Blogs").ToList();
}

using (var context = new BloggingContext())
{
context.Database.SqlCommand(
"UPDATE dbo.Blogs SET Name = 'Another Name' WHERE BlogId = 1");
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: