Issue on Mapping inherited class in .Net 4.8 with LINQ to SQL

79 Views Asked by At

I am using .Net 4.8 Framework and System.Data.Linq package.

I am trying to Map data from database to object (Child).

ChildClass inherits ParentClass, so in my thought it should be able to use Properties of ParentClass also. But I am not able to achive it.

I have tried below code so far

    public class TestClass
    {
        public void GetDataList()
        {
            try
            {
                using (var db = new DataContext(connectionString))
                {
                    string strSQL = "select 1 as ID, 'test' as Name, 5 as ChildID";
                    var ic1 = db.ExecuteQuery<ChildClass>(strSQL);
                }
            }
            catch (Exception ex)
            {

            }
        }
    }
    public class ParentClass
    {
        public int ID { get; set; }
        public string Name { get; set; }
    }
    public class ChildClass : ParentClass
    {
        public int ChildID { get; set; }
    }

In this case, I am getting an Error.

Data member 'Int32 ID' of type 'TestConsoleApp.ParentClass' is not part of the mapping for type 'ChildClass'. Is the member above the root of an inheritance hierarchy?

1

There are 1 best solutions below

0
Anuj Karki On

I able to fix the issue using Linq-to-sql and Dapper.

Linq-to-sql is used to support older code. and Dapper will fix the mapping issue.

Here is fixed code

using (var db = new DataContext(connectionString))
{
    string strSQL = "select 1 as ID, 'test' as Name, 5 as ChildID";
    var ic1 = db.Connection.Query<ChildClass>(strSQL);
}