C# 类继承在属性和sql相关方法方面的最佳实践

C# 类继承在属性和sql相关方法方面的最佳实践,c#,asp.net,.net,sql-server,C#,Asp.net,.net,Sql Server,两个问题: 我有另一个类,名为Section,它将从上面的Page类派生。但是,部分将不具有网站ID,而是具有页面ID。它们都是整数,但如何更改属性名是派生类 第二件事是,我是否应该重写Insert()方法以使用另一个sqlString?如果没有,实施这些要求的最佳方式是什么 提前感谢。我还有一个名为Section的类,它将从该类派生 以上称为页面。但是,节将不具有WebsiteID,但将 用一个PageID代替。它们都是整数,但我该怎么做呢 更改属性名称是派生类 错误在于您的页面包含secti

两个问题:


我有另一个类,名为
Section
,它将从上面的Page类派生。但是,
部分
将不具有网站ID,而是具有页面ID。它们都是整数,但如何更改属性名是派生类

第二件事是,我是否应该
重写
Insert()
方法以使用另一个
sqlString
?如果没有,实施这些要求的最佳方式是什么


提前感谢。

我还有一个名为Section的类,它将从该类派生 以上称为页面。但是,节将不具有WebsiteID,但将 用一个PageID代替。它们都是整数,但我该怎么做呢 更改属性名称是派生类

错误在于您的页面包含section对象,所以您不必从页面派生section:页面必须有section的集合

#region Properties
public int ID
{
    get;
    set;
}
public string Name
{
    get;
    set;
}
public string MetaTitle
{
    get;
    set;
}
public string MetaDescription
{
    get;
    set;
}
public virtual int WebsiteID
{
    get;
    set;    
}
public DateTime TimeStamp
{
    get;
    set;
}
#endregion Properties

#region Methods 
public void Insert()
{
    string sqlString = "INSERT INTO Pages ([name], [value], [meta_title], [meta_description], [website_id]) " +
        "VALUES (@Name, @Image, @Description, @MetaTitle, @MetaDescription, @WebsiteID);";
    SqlConnection sqlConnection =
        new SqlConnection(WebConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
    using (SqlCommand sqlCommand = new SqlCommand(sqlString, sqlConnection))
    {
        sqlCommand.Parameters.AddWithValue("@Name", this.Name);
        sqlCommand.Parameters.AddWithValue("@Image", this.Image);
        sqlCommand.Parameters.AddWithValue("@Description", this.Description);
        sqlCommand.Parameters.AddWithValue("@MetaTitle", this.MetaTitle);
        sqlCommand.Parameters.AddWithValue("@MetaDescription", this.MetaDescription);
        sqlCommand.Parameters.AddWithValue("@WebsiteID", this.WebsiteID);
        try
        {
            sqlConnection.Open();
            sqlCommand.ExecuteNonQuery();
            sqlConnection.Close();
            sqlConnection.Dispose();
        }
        catch (SqlException e)
        {
        }
    }
}

我想你的遗产可能有点少了。“部分”不是“页面”,或者是

为什么不创建一个名为
Content
或类似的基类,并具有以下属性:

class Page
{
     private Section[] sections;
     public Section[] Sections {get;set;}
}
并让
Page
扩展它,添加
WebsiteID
和添加
PageID
的部分

但我也建议将实体模型与数据访问分离。使用EntityFramework或NHibernate之类的工具来为您处理持久性,这样您就不必手动编写代码了


这样,您就可以拥有一个更为连接的模型,其中
部分
实际上引用了
页面
实体,而不是手动处理ID。而且
页面
可以以同样的方式包含
部分
(如
列表
),您可能会有一个更干净的模型。

您不认为连接对象的using语句合适吗?请只发布足够的代码来重现问题。哦,我的上帝,在仔细研究了实体框架之后,我觉得自己是个十足的白痴,因为我写了大约8个类的上述内容。天哪。谢谢
public int ID { get; set; }
public string Name { get; set; }
public string MetaTitle { get; set; }
public string MetaDescription { get; set; }
public DateTime TimeStamp { get; set; }