Reputation: 1185
In SQL database I have two tables, TablleA and TableB.
TableA
abstract is:
Column1 int IDENTITY(1,1),
Column2 varchar(30),
Column3 money
TableB
has identical schema but inverted identity as follows:
Column1 int IDENTITY(-1,-1),
Column2 varchar(30),
Column3 money
For my querying purposes in SQL I union those two tables and retain unique record identity. Now, in my C# winform application I have following methods.
private void DisplayContent(TableA tableObjectToDisplay)
private TableA FindRecord(int recordIdentity)
Since TableA
and TableB
LINQ class schemas are identical, rather than writing methods to find and display TableB
class objects, (with body identical to existing methods), I would prefer to reuse methods that utilize TableA
class.
One way would be to alter my existing methods to accept and return object
class values, test the type and cast accordingly within each methods. Property names remain the same so code could be reused. However, I find it a bit barbaric to take this route.
Is there any way to cast one LINQ class object as another LINQ class object?
Is there a common interface LINQ object bound to same database inherit from that I could use instead of barbaric object
?
Upvotes: 1
Views: 169
Reputation: 218818
Direct casting isn't going to work since the language is statically typed. Even if the classes are exactly the same in structure, there's no way for the compiler to know or guarantee that.
Are the types auto-generated? Usually that involves partial
classes, so you can define an interface and make use of the partial
classes to implement that interface. Something like this:
interface ISomething
{
int Column1 { get; }
string Column2 { get; }
decimal Column3 { get; } // or whatever the type is for money, I don't remember
}
Then add partial classes to accompany the generated partial classes. Something like this:
partial class TableA : ISomething
{
// The interface is already implemented in the generated code
}
partial class TableB : ISomething
{
// The interface is already implemented in the generated code
}
That should allow your common code to accept instances of ISomething
(hopefully more aptly named, of course) rather than TableA
or TableB
specifically:
private void DisplayContent(ISomething tableObjectToDisplay)
Upvotes: 4