ADO.NET独特的数据库

时间:2013-04-01 15:13:48

标签: ado.net

  

程序员需要的是一种概括不同数据系统的方法   以标准,一致和强大的方式。在.NET的世界里   应用程序开发,Microsoft ADO.NET满足了这一需求。代替   担心与不同数据库相关的细节   系统,使用ADO.NET的程序员专注于数据内容本身。

     

从“ADO.NET 4 Step by Step”一书

始终考虑下一个结构。

ADO.NET可以分为两个部分:

1。经典ADO.NET (DataSet,DataTables等)。在经典变体中,有不同的DB连接提供程序,每个提供程序都将DB内部数据转换为.NET。例如,MS SQL Server以一种方式保存数据而将Oracle保存在另一种方式中。因此,我们可以通过更改提供商来更改数据库。

似乎是一个神奇的药丸,但所有ADO.NET语句都是硬编码的。

对于MS SQL,前10个选择语句为SELECT TOP 10 ROWS FROM TABLE,对于Oracle SELECT ROWS FROM TABELE WHERE ROWNUM <= 10似乎更改数据库和提供商无济于事,不是吗?

2。实体框架。这个框架有内部独立的语言语句,转换为选择的DB语句,看起来真的是神奇的药丸:

LINQ - &gt;内部EF声明 - &gt; MS SQL DB,

LINQ - &gt;内部EF声明 - &gt; Oracle DB。

那么在经典的ADO.NET中,只需更改数据库并几乎独立于数据库吗?

2 个答案:

答案 0 :(得分:3)

  

那么在经典的ADO.NET中,只需更改数据库并几乎独立于数据库吗?

当然你可以,但为了能够做到这一点,我们必须揭穿这一陈述。

  

似乎是一个神奇的药丸,但所有ADO.NET语句都是硬编码的。

这不是ADO.NET的副产品 - 这是您的架构的副产品。您正在错误的位置构建SQL语句。您需要具体的,提供者特定的模型,这些模型能够构建提供者之间不同的语句。这并不像听起来那么糟糕 - 大多数陈述都可以利用反射自动生成 - 这只是特殊情况。

例如,假设我有一个这样的模型:

public class Employee
{
    public int ID { get; set; }
    public string Name { get; set; }
    public DateTime DateOfBirth { get; set; }
}

让我们说我想从中生成一个SELECT语句。好吧,我首先需要一些属性来告诉我PK是什么属性以及数据字段是什么属性:

[AttributeUsage(AttributeTargets.Property, Inherited = false, AllowMultiple = false)]
internal sealed class DataFieldAttribute : Attribute
{
    public DataFieldAttribute()
    {
    }
}

[AttributeUsage(AttributeTargets.Property, Inherited = false, AllowMultiple = false)]
sealed class PrimaryKeyAttribute : Attribute
{
    public PrimaryKeyAttribute()
    {
    }
}

现在我需要装饰那个类:

public class Employee
{
    [PrimaryKey]
    public int ID { get; set; }
    [DataField]
    public string Name { get; set; }
    [DataField]
    public DateTime DateOfBirth { get; set; }
}

现在我只需要一个简单的过程来创建SELECT语句,所以首先让我们构建一个基础数据模型类:

public abstract class DataModelBase
{
    protected string _primaryKeyField;
    protected List<string> _props = new List<string>();

    public DataModelBase()
    {
        PropertyInfo pkProp = this.GetType().GetProperties().Where(p => p.GetCustomAttributes(typeof(PrimaryKeyAttribute), false).Length > 0).FirstOrDefault();
        if (pkProp != null)
        {
            _primaryKeyField = pkProp.Name;
        }

        foreach (PropertyInfo prop in this.GetType().GetProperties().Where(p => p.GetCustomAttributes(typeof(DataFieldAttribute), false).Length > 0))
        {
            _props.Add(prop.Name);
        }
    }

    public virtual string TableName { get { return this.GetType().Name; } }

    public virtual string InsertStatement
    {
        get
        {
            return string.Format("INSERT INTO [{0}] ({1}) VALUES ({2})",
                this.TableName,
                GetDelimitedSafeFieldList(", "),
                GetDelimitedSafeParamList(", "));
        }
    }

    public virtual string UpdateStatement
    {
        get
        {
            return string.Format("UPDATE [{0}] SET {1} WHERE [{2}] = @{2}",
                this.TableName,
                GetDelimitedSafeSetList(", "),
                _primaryKeyField);
        }
    }

    public virtual string DeleteStatement
    {
        get
        {
            return string.Format("DELETE [{0}] WHERE [{1}] = @{1}",
                this.TableName,
                _primaryKeyField);
        }
    }

    public virtual string SelectStatement
    {
        get
        {
            return string.Format("SELECT [{0}], {1} FROM [{2}]",
                _primaryKeyField,
                GetDelimitedSafeFieldList(", "),
                this.TableName);
        }
    }

    protected string GetDelimitedSafeParamList(string delimiter)
    {
        return string.Join(delimiter, _props.Select(k => string.Format("@{0}", k)));
    }

    protected string GetDelimitedSafeFieldList(string delimiter)
    {
        return string.Join(delimiter, _props.Select(k => string.Format("[{0}]", k)));
    }

    protected string GetDelimitedSafeSetList(string delimiter)
    {
        return string.Join(delimiter, _props.Select(k => string.Format("[{0}] = @{0}", k)));
    }
}

现在让我们继承该数据模型:

public class Employee : DataModelBase
现在,只要我需要,我就可以获得这些陈述,这些陈述现在适用于任何具体的提供者。

然后我会使用Dapper to get the data,因为它会利用IDbConnection界面,就像你需要的那样它的速度非常快 - 而且你去了 - 一个独立于提供商的解决方案如果需要,可以很容易地扩展为构建Employee的Oracle版本。

  

这个框架有内部独立的语言语句,转换为选择的DB语句,看起来真的是神奇的药丸

当然,它可能看起来像一个神奇的药丸,但它在很多方面真的是一个诅咒。您没有灵活性(至少不容易)构建针对您的需求进行优化的语句,以支持高事务和卷数据库。你真的受这里的主人的影响。 .NET实体框架为您构建这些语句,我甚至无法计算StackOverflow上有多少问题,我如何更改利用.NET实体框架的LINQ语句生成的SQL。

答案 1 :(得分:0)

正盯着玩这个。我知道这是一个老帖子。由于上面的例子,很少修改。仍有很多工作要做

using System.Collections.Generic;
using System.Reflection;
using Dapper;
using System.Linq;
using AppAttributes;
using System.ComponentModel.DataAnnotations;
using System;

public abstract class DataModelBase
{
  protected string _primaryKeyField;
  protected List<string> _props = new List<string>();
  protected List<BuildClass> _class = new List<BuildClass>();

public DataModelBase()
{
    PropertyInfo pkProp = this.GetType().GetProperties().Where(p => p.GetCustomAttributes(typeof(KeyAttribute), false).Length > 0).FirstOrDefault();
    if (pkProp != null)
    {
        _primaryKeyField = pkProp.Name;
    }

    foreach (PropertyInfo prop in this.GetType().GetProperties().Where(p => p.GetCustomAttributes(typeof(DataFieldAttribute), false).Length > 0))
    {
        _props.Add(prop.Name);
    }

    foreach(PropertyInfo prop in this.GetType().GetProperties())
    {
        if(prop.GetCustomAttributes<ExcludeAttribute>().Count<ExcludeAttribute>() > 0) continue;
        MaxLengthAttribute maxLength = prop.GetCustomAttribute<MaxLengthAttribute>();
        MinLengthAttribute minLength = prop.GetCustomAttribute< MinLengthAttribute>();
        StringLengthAttribute stringLength = prop.GetCustomAttribute< StringLengthAttribute>();
        RequiredAttribute required = prop.GetCustomAttribute<RequiredAttribute>();
        RangeAttribute range = prop.GetCustomAttribute<RangeAttribute>();
        DataTypeAttribute dataType = prop.GetCustomAttribute<DataTypeAttribute>();
        KeyAttribute key = prop.GetCustomAttribute<KeyAttribute>();

        var kyk = prop.PropertyType;
        //var sss = kyk.FullName.;


        var cl = new BuildClass
        {
            Name = prop.Name,
            MaxLength = maxLength != null
            ? (int?)maxLength.Length
            : stringLength != null
                ? (int?)stringLength.MaximumLength : null,
            MinLength = minLength != null
            ? (int?)minLength.Length
            : stringLength != null
                ? (int?)stringLength.MinimumLength : null,
            PrimaryKey = key != null ? true : false,
            Type = prop.PropertyType.Name.ToString()
        };
        _class.Add(cl);
    }
}

[Exclude]
public virtual string TableName { get { return this.GetType().Name; } }

[Exclude]
public virtual string InsertStatement
{
    get {
        return string.Format("INSERT INTO [{0}] ({1}) VALUES ({2})",
            this.TableName,
            GetDelimitedSafeFieldList(", "),
            GetDelimitedSafeParamList(", "));
    }
}

[Exclude]
public virtual string UpdateStatement
{
    get {
        return string.Format("UPDATE [{0}] SET {1} WHERE [{2}] = @{2}",
            this.TableName,
            GetDelimitedSafeSetList(", "),
            _primaryKeyField);
    }
}

[Exclude]
public virtual string DeleteStatement
{
    get {
        return string.Format("DELETE [{0}] WHERE [{1}] = @{1}",
            this.TableName,
            _primaryKeyField);
    }
}

[Exclude]
public virtual string SelectStatement
{
    get {
        return string.Format("SELECT [{0}], {1} FROM [{2}]",
            _primaryKeyField,
            GetDelimitedSafeFieldList(", "),
            this.TableName);
    }
}

[Exclude]
public virtual string CreateStatement
{
    get {
        return "CREATE TABLE " + TableName+" (" + GetDelimetedCreateParamList(",") 
            + ", CONSTRAINT PK_"
            + _class.Where(c=>c.PrimaryKey).FirstOrDefault().Name 
            + " PRIMARY KEY(" 
            + string.Join(",", _class.Where(c=>c.PrimaryKey).Select(c=>c.Name)) + ") )";
    }
}

protected string GetDelimetedCreateParamList(string delimeter)
{
    return string.Join(delimeter, _class.Select(k => string.Format(" {0} {1} ({2}) {3}" + Environment.NewLine,
        k.Name,
        GetSqlType(k.Type),
        k.MaxLength,
        k.NotNull == true || k.PrimaryKey == true ? "NOT NULL " : ""
        //k.PrimaryKey == true ? "PRIMARY KEY" : ""

        ).Replace("()", "")) 
        );
}

protected string GetSqlType(string type)
{
    switch(type.ToUpper())
    {
        case "INT16":
            return "smallint";
        case "INT16?":
            return "smallint";
        case "INT32":
            return "int";
        case "INT32?":
            return "int";
        case "INT64":
            return "bigint";
        case "INT64?":
            return "bigint";
        case "STRING":
            return "NVARCHAR";
        case "XML":
            return "Xml";
        case "BYTE":
            return "binary";
        case "BYTE?":
            return "binary";
        case "BYTE[]":
            return "varbinary";
        case "GUID":
            return "uniqueidentifier";
        case "GUID?":
            return "uniqueidentifier";
        case "TIMESPAN":
            return "time";
        case "TIMESPAN?":
            return "time";
        case "DECIMAL":
            return "money";
        case "DECIMAL?":
            return "money";
        case "bool":
            return "bit";
        case "bool?":
            return "but";
        case "DateTime":
            return "datetime";
        case "datetime?":
            return "datetime";
        case "double":
            return "float";
        case "double?":
            return "float";
        case "char[]":
            return "nchar";


    }
    return "UNKNOWN";
}

private string CreateField(BuildClass column)
{
    return " " + column.Name + " " + column.Type + " (" + column.MaxLength + ") ";
}

protected string GetDelimitedSafeParamList(string delimiter)
{
    return string.Join(delimiter, _props.Select(k => string.Format("@{0}", k)));
}

protected string GetDelimitedSafeFieldList(string delimiter)
{
    return string.Join(delimiter, _props.Select(k => string.Format("[{0}]", k)));
}

protected string GetDelimitedSafeSetList(string delimiter)
{
    return string.Join(delimiter, _props.Select(k => string.Format("[{0}] = @{0}", k)));
}

}

public class BuildClass
{
   public string Name { get; set; }
   public string Type { get; set; }
   public bool PrimaryKey { get; set; }
   //public bool ForeignKey { get; set; }
   public int? MinLength { get; set; }
   public int? MaxLength { get; set; }
   public bool NotNull { get; set; } = false;

}