开发者

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

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 class开发者_如何学编程es but when trying to compile I get an error telling me that the property is not mapped. Is there an attribute or something I should add? Thanks in advance.


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);
     }
 }


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.


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!


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜