![](/img/trans.png)
[英]Use Reflection to get methods excluding local functions in C# 7.0?
[英]Common CRUD functions with use of reflection C#
這是我的情況,我必須創建一個通用函數以將值插入MySQL數據庫。 到目前為止,我有下面的方法。 當另一個類中沒有復合類時,此代碼可以正常工作。 如果我們在實體中具有導航屬性,則此代碼將中斷,我被困在這里。
(ORM-由於其客戶要求,我們無法使用它)
public string create(object entity){
var sql = new OdbcCommand();
var d = new StringDictionary();
var dd = new StringDictionary();
try
{
var objectType = entity.GetType();
var properties = objectType.GetProperties();
var tableName = objectType.GetCustomAttributes(false).Select(x => (x as TableAttribute).Name).FirstOrDefault();
foreach (var prop in properties)
{
if (prop.DeclaringType != typeof (BasicRequest)) // BasicRequest is base class
{
if (
prop.GetCustomAttributes(false).Where(y=>y is ColumnAttribute).Select(x => (x as ColumnAttribute)).FirstOrDefault().IsPrimaryKey)
{
continue;
}
if (prop.PropertyType.IsGenericType) // here comes the problem
{
// the problem is if a class has List of its child
objects then how to insert them since here parent
is not yet inserted.
}
if (prop.GetCustomAttributes(false).Where(y => y is ColumnAttribute).Select(x => (x as ColumnAttribute)).FirstOrDefault().IsParent)
{
// same problem here also but this time this object is
parent object of the entity
/*parentObject = prop.GetValue(entity, null);
CreateNew(parentObject);
*/
continue;
}
d[prop.GetCustomAttributes(false).Where(y => y is ColumnAttribute).Select(x => (x as ColumnAttribute).Name).FirstOrDefault()] = DBUtil.FixSQLString(Convert.ToString(prop.GetValue(entity, null)));
}
else
{
continue;
}
}
Connection coxn = ConnectionPool.GetInstance().GetCoxn(Constants.MyName,ConnectionPool.WriteServer,"db_name");
sql.Connection = coxn.odbcConnection;
sql.CommandType = CommandType.Text;
sql.CommandText = DBUtil.CreateInsert(tableName, d);
int affected = sql.ExecuteNonQuery();
if (affected != 1)
{
ErrorMessage = "Insert Failed Unexpectedly";
return "0";
}
return "1";
}
catch (Exception ex)
{
ErrorMessage = ex.Message;
return "0";
}
}
讓我們接受一個實體(這種設計不在我手中,此類已經存在,我無法更改此實體)
[Table(Name="person")]
public class Person
{
[Column(Name="id",IsPrimaryKey=true)] // Column is my custom attribute
public int Id{get;set;}
[Column(Name="name",IsPrimaryKey=true)]
public string Name{get;set;}
// this is where i'm not able get it how do i insert
// child class with the function i wrote above
[Column(IsChild=true)]
public List<Contact> contact{get;set;} // Navigation property
//Same problem with this property also
// how do i do insert for parent
[Column(IsParent=true)]
public User user{get;set;}
}
// i'll call that insert method as
Common c = new Common();
c.Create(Person p); // p will be passed as argument from controller
看起來您正在嘗試創建自己的ORM實現。 這將非常復雜,絕對不值得為客戶項目付出努力。
您可以使用代碼生成工具從數據庫結構生成數據訪問層。 例如,CodeSmith http://www.codesmithtools.com/ 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.