简体   繁体   English

.NET Core 2.0 强类型数据行

[英].NET Core 2.0 Strongly Typed DataRows

Is there a way to strongly type a DataRow in C# .NET Core 2.0 without using EF nor any ORM?有没有办法在不使用 EF 或任何 ORM 的情况下在 C# .NET Core 2.0 中强类型化 DataRow? I used datasets on vb.net, but it looks like it's not yet available.我在 vb.net 上使用了数据集,但它似乎还不可用。 Also, it looks like SqlCommandBuilder isn't available either.此外,看起来 SqlCommandBuilder 也不可用。

I used something like this in vb.net:我在 vb.net 中使用了类似的东西:

Public Sub EntityToDataSet(ByRef entity As User, ByRef dataset As MyDataSet)
Dim dr As MyDataSet.UsersRow
dr = dataset.Users.NewUsersRow()
dr.Address = entity.Address
dr.Name = entity.Name
_dataAdapterUsers.Update(dataSet)
End Sub

As you can see, the dataset provides strongly typed rows.如您所见,数据集提供了强类型行。 I want to be able to do something like this on .NET Core.我希望能够在 .NET Core 上做这样的事情。

Even if strongly typed DataSets , DataRows etc. were available using a .NET Core Stack and ADO.NET which they are not , I think you will find in the .NET Core community today that there would be very little use of DataRow or DataSet at all and certainly not as a means to enforce strong typing, for example .即使强类型的 DataSets 、 DataRows 等可以使用 .NET Core Stack 和 ADO.NET 而它们不是,我想你会在今天的 .NET Core 社区中发现很少使用 DataRow 或 DataSet all,当然不是作为强制强类型的一种手段, 例如. That concept of "strongly typed" that ADO.NET provided out of the box for some of its key objects like DataTable, DataRow, Dataset is an old school mentality. ADO.NET 为其一些关键对象(如 DataTable、DataRow、Dataset)提供开箱即用的“强类型”概念是一种老派的心态。 If you want a strongly typed solution in this day and age, you simply define your types and throw exceptions when incorrect type casting is attempted, or do not even throw exceptions, C# will throw invalid cast exceptions for you.如果您在当今时代想要一个强类型的解决方案,您只需定义您的类型并在尝试不正确的类型转换时抛出异常,或者甚至不抛出异常,C# 将为您抛出无效的转换异常。

I think it also makes sense to say that using a strongly typed DataRow/DataSet implementation is reminiscent of an implementation you might do with ASP.NET Web Forms stack circa 1999-2005.我认为说使用强类型 DataRow/DataSet 实现让人想起您可能在 1999-2005 年使用 ASP.NET Web 窗体堆栈执行的实现也是有道理的。 If I remember correctly ADO.NET DataTable and DataSet had these out of the box strongly typed features developers would utilize.如果我没记错的话,ADO.NET DataTable 和 DataSet 具有这些开箱即用的强类型功能,开发人员会使用这些功能。 But today, the best practices are always to keep things very simple and clean, no out of the box magic that Microsoft used to provide, that magic almost always led to monolithic, hard to maintain software architecture.但是今天,最佳实践总是让事情变得非常简单和干净,没有微软曾经提供的开箱即用的魔法,这种魔法几乎总是导致单一的、难以维护的软件架构。

I believe the code below is a "strongly typed" solution, using .NET Core 2.0, ADO.NET and not using EF or any other ORM, if you just do not focus on a strongly typed "DataRow" requirement which confuses me a bit that is a requirement from the University, I am guessing that using a DataRow is something you hope to achieve because it is familiar to you from past code you have written.我相信下面的代码是一个“强类型”解决方案,使用 .NET Core 2.0、ADO.NET 而不是使用 EF 或任何其他 ORM,如果你只是不关注强类型的“DataRow”要求,这让我有点困惑这是大学的要求,我猜使用 DataRow 是您希望实现的目标,因为您过去编写的代码对它很熟悉。

And keep in mind that MySQL, SQL Server, Oracle database can be designed "strongly typed", and really cannot be easily designed any other way because columns have types like: varchar , int , decimal , money , byte , guid , nvarchar etc.请记住,MySQL、SQL Server、Oracle 数据库可以设计为“强类型”,实际上不能以任何其他方式轻松设计,因为列具有以下类型: varcharintdecimalmoneybyteguidnvarchar等。

You could make every column in every database a blob or byte and then argue the database is dynamically typed but it is a bit of silly scenario.您可以将每个数据库中的每一列都设为 blob 或字节,然后争辩说数据库是动态类型的,但这有点愚蠢。

C# is a "strongly typed" language. C# 是一种“强类型”语言。

So with all that said, and as long as the University does not specifically ask that you use DataRow or DataSet to enforce strong typing, then this solution might fit the bill as it still uses ADO.NET:综上所述,只要大学没有明确要求您使用 DataRow 或 DataSet 来强制执行强类型,那么这个解决方案可能符合要求,因为它仍然使用 ADO.NET:

public class AddressModel {
    public string Address1 { get; set; } //this is a strongly typed property
    public int Zip { get; set; } //this is a strongly typed property
}

public List<AddressModel> GetAddress(int addressId) {
    List<AddressModel> addressList = new List<AddressModel>();
    cmd.CommandText = @"SELECT Address1, Zip FROM [dbo].[Address]";
    using (SqlDataReader data = cmd.ExecuteReader())
    {
        while (data.Read())
        {
            AddressModel temp = new AddressModel();
            temp.Address1 = Sql.Read<String>(data, "Address1");
            temp.Zip = Sql.Read<Int32>(data, "Zip");
            addressList.Add(temp);
        }
    }

    return addressList;
}

public static class Sql
{
    public static T Read<T>(DbDataReader DataReader, string FieldName)
    {
        int FieldIndex;
        try { FieldIndex = DataReader.GetOrdinal(FieldName); }
        catch { return default(T); }

        if (DataReader.IsDBNull(FieldIndex))
        {
            return default(T);
        }
        else
        {
            object readData = DataReader.GetValue(FieldIndex);
            if (readData is T)
            {
                return (T)readData;
            }
            else
            {
                try
                {
                    return (T)Convert.ChangeType(readData, typeof(T));
                }
                catch (InvalidCastException)
                {
                    return default(T);
                }
            }
        }
    }
}

Credit goes to this answer for the nice Read extension method that will throw Invalid Type Cast Exceptions归功于这个不错的Read扩展方法的答案,该方法将抛出 Invalid Type Cast Exceptions

Strongly-typed datasets are just c# classes generated by the visual studio designer, using ADO.net datasets.强类型数据集只是 Visual Studio 设计器使用 ADO.net 数据集生成的 c# 类。 So if ADO.net is supported (which it is, see link below), you should be able to use your existing strongly typed datasets.因此,如果支持 ADO.net(确实如此,请参见下面的链接),您应该能够使用现有的强类型数据集。 Note that I haven't tried it, but it's a topic I should research for an existing code base I have.请注意,我还没有尝试过,但这是我应该针对我拥有的现有代码库研究的主题。

https://blogs.msdn.microsoft.com/devfish/2017/05/15/exploring-datatable-and-sqldbadapter-in-asp-net-core-2-0/ https://blogs.msdn.microsoft.com/devfish/2017/05/15/exploring-datatable-and-sqldbadapter-in-asp-net-core-2-0/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM