Reputation: 673
I have some classes (entities) that represent database tables
public class ALBUM
{
public int Id { get; set; }
public string Name { get; set; }
public int Tracks { get; set; }
}
public class BOOK
{
public int Id { get; set; }
public string Author { get, set; }
}
Then to get parameters to respective stored procedures, insert, update, any
public Command getParameters(string spName, dynamic entity, Connection conn)
{
Command cmd = conn.CreateCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = spName;
// Get properties (fields) from entity (table)
PropertyInfo[] properties = entity.GetType().GetProperties();
for (int = 0; i < properties.Length; i++)
{
// here I set Parameters: name, DBType, and Value from properties
}
}
Now I call
public void Some()
{
ALBUM someAlbum = new ALBUM();
BOOK anyBook = new BOOK(); // all respective data from DB is set
Command newCommand = getParameters("myAlbumSP", someAlbum, myConnection);
Command newCommand = getParameters("mySPBooks", anyBook, myConnection);
}
How else colud I define "entity" parameter?, not to be dynamic.
It works, just I'm lookin for some other way to do it, I´m sure there is plenty of.
Upvotes: 1
Views: 278
Reputation: 898
You could use the ExpandoObject class. As Paul Sasik said:
Expando is a dynamic type designed to handle dynamic data by adding/removing members at runtime. dynamic is designed to allow .NET to interoperate with types when interfacing with dynamic typing languages such as Python and JavaScript.
https://stackoverflow.com/a/3540291/322848
Here is an article that explains the ExpandoObject:
Upvotes: 0
Reputation: 726609
In your case, entity
does not need to be dynamic
(although it is certainly OK). Using object
instead would be sufficient, because you do not call anything outside of what object
gives you. This works, because you use reflection. With dynamic
, on the other hand, you could specify properties not found on object
, and the compiler would not complain.
For example, since both ALBUM
and BOOK
have an Id
parameter, you could write something like this:
var entityId = entity.Id;
This would work as long as entity
is dynamic
; it would not work with an object
.
Upvotes: 2