0
我有一個抽象父類(Product)和兩個從它繼承的子類(Book,Software)。我需要將常用數據(父類屬性)插入到Products表中,並將子類的特定屬性插入到BookProducts和SoftwareProducts表中。將子對象的屬性插入數據庫的正確方法?
這是我想出的實現,我想知道是否有人可以提供更好的方法。
public static class Database
{
public static void SaveBook(Book book)
{
//save the product to products table and return the ID of the new row
int ProductID = saveProduct(book);
SqlConnection connection = DatabaseConnection.GetConnection();
string insertBookStatement =
"INSERT BookProducts" +
"(ProductID,Author)" +
"VALUES (@ProductID,@Author)";
SqlCommand insertBookCommand = new SqlCommand(insertBookStatement, connection);
insertBookCommand.Parameters.AddWithValue("@ProductID",ProductID);
insertBookCommand.Parameters.AddWithValue("@Author",book.Author);
try
{
connection.Open();
insertBookCommand.ExecuteNonQuery();
}
catch (SqlException ex)
{
throw ex;
}
finally
{
connection.Close();
}
}
public static void SaveSoftware(Software software)
{
int ProductID = saveProduct(software);
SqlConnection connection = DatabaseConnection.GetConnection();
string insertSoftwareStatement =
"INSERT SoftwareProducts" +
"(ProductID,VersionNumber)" +
"VALUES (@ProductID,@VersionNumber)";
SqlCommand insertSoftwareCommand = new SqlCommand(insertSoftwareStatement, connection);
insertSoftwareCommand.Parameters.AddWithValue("@ProductID", ProductID);
insertSoftwareCommand.Parameters.AddWithValue("@VersionNumber", software.VersionNumber);
try
{
connection.Open();
insertSoftwareCommand.ExecuteNonQuery();
}
catch (SqlException ex)
{
throw ex;
}
finally
{
connection.Close();
}
}
private static int saveProduct(Product p)
{
int ProductID;
SqlConnection connection = DatabaseConnection.GetConnection();
string insertProductStatement =
"INSERT Products" +
"(Code,Description,Category,Price)" +
"VALUES (@code,@Description,@Category,@Price)";
SqlCommand insertProductCommand = new SqlCommand(insertProductStatement, connection);
insertProductCommand.Parameters.AddWithValue("@Code", p.Code);
insertProductCommand.Parameters.AddWithValue("@Description", p.ShortDescription);
insertProductCommand.Parameters.AddWithValue("@Category", p.Category);
insertProductCommand.Parameters.AddWithValue("@Price", p.Price);
try
{
connection.Open();
insertProductCommand.ExecuteNonQuery();
string selectStatement = "SELECT IDENT_CURRENT('Products') FROM Products";
SqlCommand selectCommand = new SqlCommand(selectStatement, connection);
ProductID = Convert.ToInt16(selectCommand.ExecuteScalar());
}
catch (SqlException ex)
{
throw ex;
}
finally
{
connection.Close();
}
return ProductID;
}
}
您可以將XML格式傳遞給存儲過程。在SP中,您可以讀取XML數據作爲表結構。 http://msdn.microsoft.com/en-us/library/ms345117%28v=sql.90%29.aspx – 2012-02-11 15:13:09
更好的方法是使用實體框架。 – 2012-02-11 15:15:06
EF對他的問題沒有幫助。該解決方案全部是關於數據建模和軟件設計的,選擇特定的ORM技術並沒有什麼幫助。 – Tobias 2012-02-11 16:28:56