1

I am new to entity framework and started playing around with it. I am trying to use my usual structure that consists of a Core project that has raw properties. DataAccess extends core classes and adds any additional db specific property and the DBContext in this case. Business extends DataAccess and has all business logic. Finally, a Models project where multiple models may extend each business class for different purposes.

My class in Core is something like this:

public class Blog
{
    public int BlogId { get; set; }
    public string Url { get; set; }
}

My DataAcceess got a context class like this:

public class MyContext : DbContext
{
    public DbSet<Blog> Blogs { get; set; }
}

And my Business got this:

public class Blog : DataAccess.Blog
{
    public void Add()
    {
        using (var db = new MyContext())
        {
            db.Blogs.Add(this);
            db.SaveChanges();
        }
    }
}

Finally my Models contains:

public class BlogModel : Business.Blog {}

Now I get an error that the entity type BlogModel doesn't exist. The table's name is Blog not BlogModel. I have tried the following:

  1. Adding [Table("Blog")] in DataAccess, Business and Model
  2. casting this as (Blog)this. The type still stays the same
  3. Creating a property Blog Current => this trying to change it's type.

Update: happens even when the model is named Blog

Neville Nazerane
  • 6,622
  • 3
  • 46
  • 79
  • Well, I can't say of that's "by design" or is a current implementation bug/limitation, but all EF Core methods receiving entity instances ('Add`, `Attach`, `Remove`, `Update` etc.) uses `entity.GetType()` method and requires the returned type to be a "entity type". Hence passing derived type intances as in your case won't work. – Ivan Stoev Feb 04 '18 at 17:10
  • well as mentioned in this bug report, apparently it isn't a bug https://github.com/aspnet/EntityFrameworkCore/issues/8728 – Neville Nazerane Feb 04 '18 at 21:04
  • but isn't this exactly what `[Table()]` is meant for? – Neville Nazerane Feb 04 '18 at 21:05
  • That's different subject. In your case, the only "entity" class is `Blog` from `DbSet`. See [Including & Excluding Types](https://learn.microsoft.com/en-us/ef/core/modeling/included-types). – Ivan Stoev Feb 05 '18 at 00:05
  • yeah, after testing what i have mentioned in the update, i realized how DbSet actually works – Neville Nazerane Feb 05 '18 at 00:57
  • thanks for the link. however it doesn't look like it an help my case without creating circular references. do you know of any git samples that use ef core with business logic? – Neville Nazerane Feb 05 '18 at 03:25

0 Answers0