C# HDI:将Linq上的属性集约束到Sql类

C# HDI:将Linq上的属性集约束到Sql类,c#,linq-to-sql,C#,Linq To Sql,如何将Linq上的属性设置器约束到Sql类 我有一个需要验证的自定义字段,设计器类可以重写 我有可以工作的重写器setter方法,但是如何限制linqtosql类上的设置 public partial class Frequency : INotifyPropertyChanging, INotifyPropertyChanged { public void SetStartTime(TimeSpan startTime) { if(startTime.Days

如何将Linq上的属性设置器约束到Sql类

我有一个需要验证的自定义字段,设计器类可以重写

我有可以工作的重写器setter方法,但是如何限制linqtosql类上的设置

public partial class Frequency : INotifyPropertyChanging, INotifyPropertyChanged
{
    public void SetStartTime(TimeSpan startTime)
    {
        if(startTime.Days > 0){throw new Exception("No day value is valid for start time value";}
        this._StartTime = string.Format("{0}:hh\\:mm\\:ss", startTime);
    }
    public TimeSpan GetStartTime()
    {
        IEnumerable<int> startTime = this._StartTime.Split(':').Cast<int>();
        return new TimeSpan(startTime.ElementAt<int>(0), startTime.ElementAt<int>(1), startTime.ElementAt<int>(2));
    }
}
公共部分类频率:INotifyPropertyChanged,INotifyPropertyChanged
{
公共无效设置开始时间(TimeSpan startTime)
{
如果(startTime.Days>0){抛出新异常(“没有日期值对开始时间值有效”}
这个.u StartTime=string.Format(“{0}:hh\\\:mm\\:ss”,StartTime);
}
公共时间跨度GetStartTime()
{
IEnumerable startTime=this._startTime.Split(':').Cast();
返回新的时间跨度(startTime.ElementAt(0)、startTime.ElementAt(1)、startTime.ElementAt(2));
}
}

如果使用LINQ to SQL类设计器,LINQ 2 SQL具备克服此问题所需的一切

假设您的表有一个Int32类型的列“Number”。 设计师将创建:

字段->\u编号

属性->编号

方法->OnNumberChanging(int值)

方法->OnNumberChanged()

最后两个方法是部分的。这意味着在从数据库刷新类的情况下,您不必接触设计器生成的文件

通过在另一个文件中创建以下内容:

public partial class MyLinqToSqlClass
{
    partial void OnNumberChanging(int value)
    {
        //your code here
        //throw exception if necessary when validating
    }
}
你得到你需要的

在更改字段值之前,在Number属性权限的set方法内调用这段代码

这样,您就不用担心使用属性的set方法


希望这能有所帮助。

我的一个想法是编写一个facade wrapperGood point!Linq to Sql类实现INotifyPropertyChanged,我可以重写或部分添加到OnChange方法!