C# 如何使用实体框架代码优先方法将 double[] 数组存储到数据库

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15220921/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 14:32:05  来源:igfitidea点击:

How to store double[] array to database with Entity Framework Code-First approach

c#.netentity-frameworkef-code-firstfluent-interface

提问by jonas

How can I store an array of doubles to database using Entity Framework Code-First with no impact on the existing code and architecture design?

如何使用 Entity Framework Code-First 在不影响现有代码和架构设计的情况下将双精度数组存储到数据库?

I've looked at Data Annotation and Fluent API, I've also considered converting the double array to a string of bytes and store that byte to the database in it own column.

我查看了数据注释和 Fluent API,我还考虑将双数组转换为字节字符串并将该字节存储到数据库中它自己的列中。

I cannot access the public double[] Data { get; set; }property with Fluent API, the error message I then get is:

我无法使用public double[] Data { get; set; }Fluent API访问该属性,然后我收到的错误消息是:

The type double[]must be a non-nullable value type in order to use it as parameter 'T'.

该类型double[]必须是不可为空的值类型才能将其用作参数“T”。

The class where Datais stored is successfully stored in the database, and the relationships to this class. I'm only missing the Datacolumn.

Data存储的类成功存储在数据库中,以及与该类的关系。我只是错过了Data专栏。

采纳答案by jonas

Thank you all for your inputs, due to your help I was able to track down the best way to solve this. Which is:

感谢大家的投入,由于您的帮助,我能够找到解决此问题的最佳方法。这是:

 public string InternalData { get; set; }
 public double[] Data
 {
    get
    {
        return Array.ConvertAll(InternalData.Split(';'), Double.Parse);                
    }
    set
    {
        _data = value;
        InternalData = String.Join(";", _data.Select(p => p.ToString()).ToArray());
    }
 }

Thanks to these stackoverflow posts: String to Doubles arrayand Array of Doubles to a String

感谢这些 stackoverflow 帖子: String to Doubles arrayArray of Doubles to a String

回答by Joffrey Kern

You can do a thing like this :

你可以做这样的事情:

    [NotMapped]
    public double[] Data
    {
        get
        {
            string[] tab = this.InternalData.Split(',');
            return new double[] { double.Parse(tab[0]), double.Parse(tab[1]) };
        }
        set
        {
            this.InternalData = string.Format("{0},{1}", value[0], value[1]);
        }
    }

    [EditorBrowsable(EditorBrowsableState.Never)]
    public string InternalData { get; set; }

回答by Nathan White

I know it is a bit expensive, but you could do this

我知道它有点贵,但你可以这样做

class Primitive
{
    public int PrimitiveId { get; set; }
    public double Data { get; set; }

    [Required]
    public Reference ReferenceClass { get; set; }
}

// This is the class that requires an array of doubles
class Reference
{
    // Other EF stuff

    // EF-acceptable reference to an 'array' of doubles
    public virtual List<Primitive> Data { get; set; }
}

This will now map a single entity (here 'Reference') to a 'list' of your Primitive class. This is basically to allow the SQL database to be happy, and allow you to use your list of data appropriately.

现在,这会将单个实体(此处为“参考”)映射到原始类的“列表”。这基本上是为了让 SQL 数据库满意,并允许您适当地使用您的数据列表。

This may not suit your needs, but will be a way to make EF happy.

这可能不适合您的需求,但将是让 EF 满意的一种方式。

回答by Husein Roncevic

It would be far easier if you use List<double>rather then double[]. You already have a table that stores your Datavalues. You probably have foreign key from some table to the table where your double values are stored. Create another model that reflects the table where doubles are stored and add foreign key mappings in the mappings class. That way you will not need to add some complex background logic which retrieves or stores values in a class property.

如果您使用List<double>而不是然后会容易得多double[]。您已经有一个表来存储您的Data值。您可能有从某个表到存储双精度值的表的外键。创建另一个模型来反映存储双精度的表,并在映射类中添加外键映射。这样你就不需要添加一些复杂的后台逻辑来检索或存储类属性中的值。

回答by Jacob Brewer

Nathan White has the best answer (got my vote).

Nathan White 给出了最好的答案(得到了我的投票)。

Here is a small improvement over Joffrey Kern's answer to allow lists of any length (untested):

这是对 Joffrey Kern 的回答的一个小改进,以允许任何长度的列表(未经测试):

    [NotMapped]
    public IEnumerable<double> Data
    {
        get
        {
            var tab = InternalData.Split(',');
            return tab.Select(double.Parse).AsEnumerable();
        }
        set { InternalData = string.Join(",", value); }
    }

    [EditorBrowsable(EditorBrowsableState.Never)]
    public string InternalData { get; set; }

回答by Pavel B.

Don't use double[] use List insted.

不要使用 double[] 使用 List 插入。

Like this.

像这样。

public class MyModel{
    ...
    public List<MyClass> Data { get; set; }
    ...
}

public class MyClass{
    public int Id { get; set; }
    public double Value { get; set; }
}

All that solution that I see there are bad, because:

我看到的所有解决方案都很糟糕,因为:

  1. If you create table, you don't want to store data like this: "99.5,89.65,78.5,15.5" that's not valid! Firstly its a string that means if you can type letter into it and at the moment when your ASP.NET server call double.Parse it will result in FormatException and that you really don't want!

  2. It's slower, because your server must parse the string. Why parse the string instead getting almost ready data from SQL Server to use?

  1. 如果你创建表,你不想存储这样的数据:“99.5,89.65,78.5,15.5”这是无效的!首先它是一个字符串,这意味着如果您可以在其中键入字母,并且当您的 ASP.NET 服务器调用 double.Parse 时,它​​将导致 FormatException 并且您真的不想要!

  2. 它更慢,因为您的服务器必须解析字符串。为什么要解析字符串而不是从 SQL Server 获取几乎准备好的数据来使用?