from t in db.tipos1 select t will give you an IEnumerable. You need to change it so that it just returns the one you want
Casting exception with Entity framework and abstract class
-
01-10-2022 - |
Question
I´m new in entity framework. I´m using EF6 with VS2013.
I need to implement a database from "code-first" approach. The problem is that i´m using an abstract class and i can´t understand why the next pice of code doesn´t work:
public abstract class AClaseT1
{
//private int idT1;
[Key]
public int idT1
{ get; set; }
}
public class ClaseT1Dev1:AClaseT1
{
//private int dataT1;
public int dataT1
{ get; set; }
}
public class Contexto : DbContext
{
public DbSet<AClaseT1> tipos1 { get; set; }
}
class Program
{
static void Main(string[] args)
{
Database.SetInitializer(new MigrateDatabaseToLatestVersion<Contexto, Configuration>());
using(var db = new Contexto())
{
Console.WriteLine("Int for Tipo1:");
int d = Console.Read();
ClaseT1Dev1 t1 = new ClaseT1Dev1() { dataT1 = d };
db.tipos1.Add(t1);
db.SaveChanges();
ClaseT1Dev1 query = (ClaseT1Dev1)from t in db.tipos1
select t;
Console.WriteLine("Int obtenido de Tipo1 metido en BDD: {0}", query.idT1);
Console.Read();
}
}
When i run the app, it breaks at the "query" line, because it can´t make the casting... Is there a way to make it works? I need a table feeded with different derived objects from the base abstract class (i think it is a TPC inheritance approach).
Thanks for your help!!!
EDIT:
The exact exception thrown at the "query" line is:
InvalidCastException was unhandled
An unhandled exception of type 'System.InvalidCastException' occurred in PruebaCodeFirstDB.exe
Additional information: It is not possible to convert an object of type 'System.Data.Entity.Infrastructure.DbQuery`1[PruebaCodeFirstDB.AClaseT1]' to type 'PruebaCodeFirstDB.ClaseT1Dev1'.
Solution