有许多查询和访问类属性的 C#/ Entity Framework 示例,其中该类是另一个类的属性(而不是子类)。
这里的问题是如何使用 Entity Framework 从 SQL Server 查询并访问作为任何类的导航属性的子类。
我也找不到关于如何查询和访问不是任何类的导航属性的子类的示例。
我只是不明白为什么微软没有这样一个基本的例子。
//问题:如何使用 select 创建查询来访问 rssBlog(Blog 的子类)的属性? //问题:如何迭代db(数据库上下文)以获取rssBlog.RssFeed的所有值
下面是来自 Microsoft 的工作示例代码,其中插入了问题:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.Entity;
using System.Diagnostics;
namespace BCodeFirstNewDatabaseSample_TPT
{
class Program
{
static void Main(string[] args)
{
try
{
using (var db = new BloggingContext())
{
// Create and save a new Blog
Console.Write("Enter a name for a new Blog: ");
var name = Console.ReadLine();
var blog = new Blog { Name = name };
db.Blogs.Add(blog);
var rssBlog = new RssEnabledBlog
{
RssFeed = "rssFeed1"
};
db.Blogs.Add(rssBlog);
db.SaveChanges();
// Display all Blogs from the database
var query = from b in db.Blogs
orderby b.Name
select b;
//每个类的 Entity Framework 类型:访问不是另一个类的导航属性的子类 //问题:如何使用 select 创建查询来访问 rssBlog(Blog 的子类)的属性?
//问题:如何迭代db.Blogs以获取rssBlog.RssFeed的所有值
Console.WriteLine("All blogs in the database:");
foreach (var item in query)
{
//这仅显示如何访问 Blog(RssEnabledBlog 的父级)。 //我也想访问rssBlog.RssFeed。怎么办?
Console.WriteLine(item.Name);
}
Console.WriteLine("Press any key to exit...");
Console.ReadKey();
}
}
catch (Exception e)
{
Console.Write("exception {0}",e.Message);
}
}
}//program
public class Blog
{
public int BlogId { get; set; }
public string Name { get; set; }
public DateTime? Datetime { get; set; }// make DataTime nullable to avoid exception?
public virtual List<Post> Posts { get; set; }
}
public class RssEnabledBlog : Blog
{
public string RssFeed { get; set; }
}
public class Post
{
public int PostId { get; set; }
public string Title { get; set; }
public string Content { get; set; }
public int BlogId { get; set; }
public virtual Blog Blog { get; set; }
}
public class BloggingContext : DbContext
{
public DbSet<Blog> Blogs { get; set; }
public DbSet<Post> Posts { get; set; }
public BloggingContext()
{//Data Source=.\SQLEXPRESS;Initial Catalog=BCodeFirstNewDatabaseSample_TPT.BloggingContext;Integrated Security=True;MultipleActiveResultSets=True;
Debug.Write(Database.Connection.ConnectionString);
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{// Thismapping creates Blog and RssEnabledBlog tables
modelBuilder.Entity<Blog>()
.Map(m => m.ToTable("Blogs"));
//base.OnModelCreating(modelBuilder);
}
}
}
这段代码有效。这是 SSMS 屏幕快照:(我是新用户...我还无法发布图像)
谢谢。
最佳答案
关键是你能做到
from reb in db.Blogs.OfType<RssEnabledBlog>()
OfType
是获取基类的子类型的方法。
然后您可以继续,例如
orderby reb.Name
select new { reb.Name, reb.RssFeed }
关于entity-framework - 每个类的 Entity Framework 类型 : C#, 访问不是另一个类的导航属性的子类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14003438/