如何在linq类中添加带参数的另一个构造函数(表)

时间:2009-05-06 08:33:13

标签: c# asp.net linq linq-to-sql

我在ASP.NET项目中使用LINQ to SQL。在插入表时,我需要将值转换为特定的表对象,我需要插入。

为此我在该表中创建了一个带有参数的新构造函数,以便我可以将我的值赋给该表对象,分配功能正在工作但插入(obj.TS_Questions.InsertOnSubmit(mytableobject);时)我得到null异常。

我的代码::

default constructor for my table

public TS_Question()
        {
            this._TS_Options = new EntitySet<TS_Option>(new Action<TS_Option>(this.attach_TS_Options), new Action<TS_Option>(this.detach_TS_Options));
            this._TS_QuestGroups = new EntitySet<TS_QuestGroup>(new Action<TS_QuestGroup>(this.attach_TS_QuestGroups), new Action<TS_QuestGroup>(this.detach_TS_QuestGroups));
            this._TS_QuestRecords = new EntitySet<TS_QuestRecord>(new Action<TS_QuestRecord>(this.attach_TS_QuestRecords), new Action<TS_QuestRecord>(this.detach_TS_QuestRecords));
            this._TS_Admin = default(EntityRef<TS_Admin>);
            this._TS_LevelType = default(EntityRef<TS_LevelType>);
            this._TS_OptionTypeLT = default(EntityRef<TS_OptionTypeLT>);
            OnCreated();
        }

我创建的构造函数

    public TS_Question(Guid Quest_QuestIDBL, string Quest_NameBL, Nullable<Guid> Quest_OptionTypeIDBL, Guid Quest_AdminIDBL, Guid Ques_LevelIDBL, int Quest_TimeBL, int Quest_MarkBL, string Qest_ExplanationBL, Nullable<bool> Qest_IsMultipleAnswerBL)
    {

        this._TS_Options = new EntitySet<TS_Option>(new Action<TS_Option>(this.attach_TS_Options), new Action<TS_Option>(this.detach_TS_Options));
        this._TS_QuestGroups = new EntitySet<TS_QuestGroup>(new Action<TS_QuestGroup>(this.attach_TS_QuestGroups), new Action<TS_QuestGroup>(this.detach_TS_QuestGroups));
        this._TS_QuestRecords = new EntitySet<TS_QuestRecord>(new Action<TS_QuestRecord>(this.attach_TS_QuestRecords), new Action<TS_QuestRecord>(this.detach_TS_QuestRecords));
        this._TS_Admin = default(EntityRef<TS_Admin>);
        this._TS_LevelType = default(EntityRef<TS_LevelType>);
        this._TS_OptionTypeLT = default(EntityRef<TS_OptionTypeLT>);
        OnCreated();

        this._Quest_QuestID = Quest_QuestIDBL;
        this._Quest_Name = Quest_NameBL; 
        if (Quest_OptionTypeIDBL != null)
        {
            this._Quest_OptionTypeID = Quest_OptionTypeIDBL;
        }
        this._Quest_AdminID = Quest_AdminIDBL;
        this._Ques_LevelID = Ques_LevelIDBL;
        this._Quest_Time = Quest_TimeBL;
        this._Quest_Mark = Quest_MarkBL;
        this._Qest_Explanation = Qest_ExplanationBL;
        this._Qest_IsMultipleAnswer = Qest_IsMultipleAnswerBL;

    }

请帮我解决这个问题

2 个答案:

答案 0 :(得分:2)

老实说,我看起来并不太深,但看起来OnCreated坐在远北方......你可能想在设置变量后调用它。除此之外,我要说确保你正确地初始化调用构造函数的方法中的所有内容。

答案 1 :(得分:2)

您可以像这样调用默认构造函数,它对我来说很好用:

 public partial class MyClass
{
    public MyClass(string fieldValue1,int fieldValue2)
        : this()
    {
        this.field1= fieldValue1;
        this.field2 = fieldValue2;
    }
}

如果这样做,您可以阅读有关在C#here中使用构造函数的更多信息。