Maris
Maris

Reputation: 4776

How to enable mapping the private property of the entity

At the begining I have to say sorry for my english.

I'm using EntityFramework and code-first way. I have one idea in my head but I dont know how to make it real. I'm not the begginer in programming, but I was always using fluent NHibernate.

I have one entity:

public class User
{
    [Key]
    public Int32 Id { get; set; }
    public String Name { get; set; }
    // This property should be mapped on DB
    private String Surname { get; set; }

    // This one shouldn't be mapped
    public String GetSurname { get { return Surname; } set { Surname = "SomePrefix." + value; }   }
}

Question 1. How can I map the private property of the entity?

I can't access this private property in my ovverride of OnModelCreating() in context.

Question 2. How can I disable the mapping of the one public property?

As the result I want to get: When I try to set the Surname i add the prefix in the begining.

Upvotes: 2

Views: 839

Answers (1)

undefined
undefined

Reputation: 34238

Entity framework does not provide a way of mapping private properties as it needs to read/write values to them, so it must have at least a public get/set for properties.

In answer to your second question you can either use the modelbuilder (my preferred way of describing your mappings as below)

modelBuilder.Entity<User>().Ignore(u=>u.GetSurname);

or add an attribute

[NotMapped]
private String Surname { get; set; }

Upvotes: 2

Related Questions