Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework Type per Class : C#, Accessing child subclass that is NOT a navigation property of another class

There are many C# / Entity Framework examples of querying and accessing property of a class where the class is a property (not a subclass) of another class.

So here is a question on how to query and then access a subclass that is a navigation property of any class from SQL server using Entity Framework.

There is also NO example I could find on how to query and access a subclass that is NOT a navigation property of any class.

I just do not understand why Microsoft do not have such a rudimentary example.

//Question: How do I create a query to access property of rssBlog (a subclass of Blog) using select? //Question: How do I iterate db (database context) to get all values of rssBlog.RssFeed

Below is a working sample code from Microsoft with inserted questions:

    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 Type per Class : Accessing child subclass that is not a navigation property of another class //Question: How do I create a query to access property of rssBlog (a subclass of Blog) using select?

//Question: How do I iterate db.Blogs to get all values of rssBlog.RssFeed

                Console.WriteLine("All blogs in the database:");
                foreach (var item in query)
                {

// This show only how to access Blog, a parent of RssEnabledBlog. //I wans to access rssBlog.RssFeed also. How?

                    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);
    }
}

}

This code works . Here is SSMS screen snapshot: (Am a new user... I cannot post an image yet)

Thanks.

like image 424
CodeForPeace Avatar asked Nov 03 '22 08:11

CodeForPeace


1 Answers

The key is that you can do

from reb in db.Blogs.OfType<RssEnabledBlog>()

OfType is the method to fetch sub types of a base class.

Then you can proceed with e.g.

orderby reb.Name
select new { reb.Name, reb.RssFeed }
like image 152
Gert Arnold Avatar answered Nov 08 '22 09:11

Gert Arnold