guneysus
guneysus

Reputation: 6502

Why Virtual Method of Derived Class is not able to be use

First of all, although the code shown below contains Entity Framework, this question is completely related to OOP and C#.

I have a class derived from DbContext, having virtual property haberler and a derived class MyDbContext derived from DbContext.

public class HaberContext : DbContext
  {
     public virtual DbSet<Haber> haberler { get; set; }
  }

public class Haber { }

Instanting MyClass with like haberler

DbContext context = new HaberContext();  // [ERROR]

with like this even if using new HaberContext(); prevent me to use the virtual property named haberler

Error 1 System.Data.Entity.DbContext does not contain a definition for haberler and no extension method haberler accepting a first argument of type System.Data.Entity.DbContext could be found (are you missing a using directive or an assembly reference?) c:\csharpprojects\entitycodefirst\entityframework-haberportal\gui.cs
37 27 EntityFrameWork-HaberPortal

Notice that DbContext is the base class of HaberContext

I have to instantiate the MyDbContext with:

HaberContext context = new HaberContext(); // [OK]

Or with Implicitly Typed Local Variable like this:

var context = new HaberContext();  // [OK]

Upvotes: 2

Views: 112

Answers (2)

Darksheao
Darksheao

Reputation: 114

If you are instantiating a class you must have the stored datatype being the "youngest", but if you can still access the child type as a parent type, however you will loose access to child specific methods. You must cast this from an instantiated object though.

DbContext context = new HaberContext(); //will not work

HaberContext Hcontext = new HaberContext();
var context = (DbContext)Hcontext; //cast done

But even though you will be able to access context as a DbContect object in this case, it will still have the type of HarberContext.

Refer to this post for more info: cast child object as parent

Upvotes: 1

David
David

Reputation: 10708

This is a casting issue, and has to to with the run-time vs. the compiler-time identity of variable context.

When you declare DbContext context, you're creating a variable. No matter what goes in that variable, the compiler only knows of it as a Dbcontext. This may be a HaberContext at runtime, but it's still only DbContext at compile time, so the compiler can't attach methods or properties from HaberContext.

There are several ways in which this can be a good thing, such as being able to reassign context later in your control flow, or exposing properties/methods as a type which is implemented by a nonpublic type (both the Type class and IEnumerable interface make use of this under the hood in .NET)

Upvotes: 4

Related Questions