Entity Framework Code First List Property Mapping

后端 未结 2 1071
孤独总比滥情好
孤独总比滥情好 2020-12-05 14:09

I am working with Entity Framework Code first. I have a simple model:

public class Variable
{
    public string Name { get; set; }

    public int Id { get;          


        
相关标签:
2条回答
  • 2020-12-05 14:57

    No, EF doesn't have any type converters or custom type mappers as alternative to model binders from MVC. You must always use some hack to force persistence. Another way to do the same is mapping TextOptions as collection of related entities. It will make your separation of concerns better but it will complicate your model and working with Variable.

    public class Variable
    {
        public string Name { get; set; }
    
        public int Id { get; set; }
    
        public IList<TextOption> TextOptions
        {
            get;
            set;
        }
    }
    
    public class TextOption
    {
        public int Id { get; set; }
        public string Text { get; set; }
    }
    
    0 讨论(0)
  • 2020-12-05 15:10

    A 3rd option would be to do the serialization using JSON.NET.

    I ran some performance tests for write scenarios using the 3 options listed on this thread (String split serialization, JSON.NET, and introducing an entity) and found that JSON.NET yields the best performance.

    Preliminary write results of 200 equal entities (see source code here and run the test yourself):

    • Time to write entities using string serializer: 896 miliseconds
    • Time to write entities using json serializer: 516 miliseconds
    • Time to write entities using multiple entities: 706 miliseconds

    Sample using JSON serializer:

    public class VariableJson
    {
        public string Name { get; set; }
    
        public int Id { get; set; }
    
        public virtual IList<string> TextOptions
        {
            get
            {
    
                return _TextOptions;
    
            }
            set
            {
                _TextOptions = value;
            }
        }
    
        private IList<string> _TextOptions;
    
        public string TextOptionsSerialized
        {
            get
            {
                return JsonConvert.SerializeObject(_TextOptions);
            }
            set
            {
                _TextOptions = JsonConvert.DeserializeObject<IList<string>>(value);                    
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题