我应该如何定义,可以采取各种数据类型的EF场? [英] How should I define a field that can take various data types in EF?

查看:177
本文介绍了我应该如何定义,可以采取各种数据类型的EF场?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的POCO类如下:

public class FilterParameter
{
    public int Id { get; set; }

    [Required]
    public virtual UserFeatureSetting UserFeatureSetting { get; set; }

     [Required]
    [MaxLength(450)]
    public String ParameterName { get; set; }

    public object ParameterValue { get; set; }

}

而产生迁移code未创建的parameterValue领域。

but the generated migration code is not creating the ParameterValue field.

CreateTable("dbo.FilterParameters", c => new {
           Id = c.Int(nullable: false, identity: true),
           ParameterName = c.String(nullable: false, maxLength: 450),
           UserFeatureSetting_Id = c.Int(nullable: false),
   })
   .PrimaryKey(t => t.Id)
   .ForeignKey("dbo.UserFeatureSettings", t => t.UserFeatureSetting_Id, cascadeDelete: false)
   .Index(t => t.UserFeatureSetting_Id);

是否有其他类型,我应该使用 - ?或周围的工作

Is there an alternative type I should be using - or a work around?

推荐答案

什么是通常做的是如

// define your 'real field' as string, byte[] and/or define column type ntext, binary etc.
public string Value {get;set;}

// and make a wrapper property
[NotMapped]
public object ValueWrapper
{
    get { return YourParser.Deserialize(this.Value); }
    set { this.Value = value.Serialize(); }
}  

...,并使用一些解析器/格式化 - 某种序列化(取决于你所拥有的是文字,一滴,XML等psented更好地重复$ P $)。

...and use some parser/formatter - serialization of some sort (depending on whether what you have is better represented by text, blob, xml etc.).

您当然应该缓存的反序列化值,如果价格昂贵等。

You should of course 'cache' the deserialized value if expensive etc.

此外,您可能会或可能不会需要存储参数类型旁边 - 这取决于你的对象和序列化格式基本。

Also, you may or may not need to store the ParameterType alongside - which depends on your object and serialization format basically.

例如。 EF / code-首先使用二进制存储EDMX模型转换成 __ MigrationHistory 表 - 他们使用相同的方法(低级别只)

e.g. EF/code-first uses binary to store the Edmx model into __MigrationHistory table - and they use the same approach (lower-level just).

如果你只需要保存/加载不同的原始类型每次(如一旦它的INT,另一次是文本等)

If you only need to save/load different 'primitive types' each time (like once it's int, another time it's text etc.)

...那么你可能有一些更多的选择(继承,也许等) - 但没有我建议你多
。 我preFER于任何其他的第一种方法为那种数据很可能没有关系方面可用,所以它不会不管你如何存储它的大部分时间。

...then you may have some more options (inheritance maybe etc.) - but nothing I'd recommend much.
I prefer the first approach over any other as that kind of data is likely not usable in terms of relationships, so it doesn't matter how you store it most of the time.

这篇关于我应该如何定义,可以采取各种数据类型的EF场?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆