zaq
zaq

Reputation: 2661

Persisting an object using Entity Framework 6.1.2 that includes an interface

I am having some difficulty persisting some objects to a SQL Server DB using Entity Framework. I am trying to do something like the following using the code first methodology:

public class ObjectA
{
    public string Name { get; set; }
    public IMyInterface InterfaceObject { get; set; }
    public ObjectD AnotherObject { get; set; }
}

public interface IMyInterface
{
}

public class ObjectB : IMyInterface
{
    public string SomePropertyB { get; set; }
}

public class ObjectC : IMyInterface
{
    public string SomePropertyC { get; set; }
}

public class ObjectD
{
    public string SomePropertyD { get; set; }
}

My Application Context class contains the following:

    public DbSet<ObjectA> ObjectA { get; set; }
    public DbSet<ObjectB> ObjectB { get; set; }
    public DbSet<ObjectC> ObjectC { get; set; }
    public DbSet<ObjectD> ObjectD { get; set; }

After updating the database, it contains tables for each of the above entities. When I attempt to save ObjectA using context.SaveChanges(), data from ObjectA and ObjectD are persisted, but the ObjectB or ObjectC behind InterfaceObject is not persisted.

Is what I am attempting to do even possible? If not, does anyone have any ideas on other ways to persist ObjectA so that it can have only one instance of either ObjectB or ObjectC, but not both?

Upvotes: 0

Views: 57

Answers (1)

zaq
zaq

Reputation: 2661

I solved this problem by making the interface an abstract class with an Id field:

public interface IMyInterface
{
        [Key]
        public int Id { get; set; }
}

Now in the database, it is using a table per hierarchy to represent the classes in question.

Upvotes: 2

Related Questions