Creating a non mapped property in an entity (entity framework)

前端 未结 4 2086
[愿得一人]
[愿得一人] 2020-12-09 07:32

I want to create a custom property on one of my entities mapped from the database, however this property is not mapped to the database, I created the property using partial

相关标签:
4条回答
  • 2020-12-09 08:03

    You can also mark your property with [NotMapped] attribute or use Ignore method from fluent API.

    Property

    public class EntityName
    {
        [NotMapped]
        private string PropertyName { get; }
    }
    

    Fluent API

     public class Entities : DbContext
     {
        public DbSet<EntityType> Users { get; set; }
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
           // Some database configuration
           modelBuilder.Entity<EntityType>()
                 .Ignore(i => i.PropertyName);
         }
     }
    
    0 讨论(0)
  • 2020-12-09 08:05

    I'm seriously late to the conversation, but you also want to mark the partial as serializable and the property as serializable - if you ever plan to JSON or serialize the objects:

    [Serializable()] 
    public partial class MyClass {
        private System.Nullable<int> _Age;
        [global::System.Runtime.Serialization.DataMemberAttribute(Order = 4)] 
        public System.Nullable<int> Age {
                ...
        }
    }
    

    Both the [Serializable()] and the [global:] directives are needed. If you excluded the [global:], any time you serialized it, it'd be ignored and not included in the serialization.

    0 讨论(0)
  • 2020-12-09 08:10

    This page really helped me. I'll add exactly what I added to my mapping configuration after seeing Kniganapolke's answer.

     public TheObjectName()
       {
           this.HasKey(t => t.ID);
           this.Ignore(t => t.IsProcess); //we don't want EF to worry about this
        }
    

    Thanks everyone, thanks SO!

    0 讨论(0)
  • 2020-12-09 08:18

    Use partial classes to add the properties or methods you want added. E.g.

    namespace WhateverNamespaceYourEntityModelIsIn
    {
        public partial class  TheNameOfYourEntity
        {
              public string MyNewProperty { get; set; }
        }
    }
    

    and that should do you.

    0 讨论(0)
提交回复
热议问题