EF Core Backing fields - expose property as another type?

前端 未结 2 2015
遇见更好的自我
遇见更好的自我 2020-12-19 00:42

Assume I have an EF entity class Person, with a PhoneNumber on it. PhoneNumber is stored as a string type, but I want all accesses on the Person to go through Phone which h

2条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-19 01:25

    The only way I've found that works in EF Core 2.0 is to create a public property with getters/setters with a name that does not match your backing field and mark it as NotMapped, like so:

        [NotMapped]
        [Display(Name = "Fire Type")]
        public Enums.FireType Type
        {
            get
            {
                Enums.FireType type;
                if (!Enum.TryParse(_fireType, out type))
                    type = Enums.FireType.Fire; // default
    
                return type;
            }
            set
            {
                _fireType = value.ToString();
            }
        }
        
        private string _fireType;
    

    Then in your DbContext's OnModelCreating method, tell it to create a column on the database table that acts like a backing property:

            // backing properties
            modelBuilder.Entity()
                .Property("FireType")
                .HasField("_fireType")
                .UsePropertyAccessMode(PropertyAccessMode.Field);
    

    With that, I was finally able to create a successful migration that allowed me to have a private field on my model, a public transformative property on the model, and a single properly-named column in my database table. The only catch is that the public property and the private field can't share the same name (without sharing the same type), but that wasn't going to be the case for you, anyway.

提交回复
热议问题