2

I have the below dbcontext.cs and the corresponding table.cs which define the DAL in my MVC using entity framework.

The List table in my database does not have a column C but I would like the entity to get the ID,A,B values from DB and get the C from code. Is this possible if so what is the best approach.

The below code fails giving an exception "Invalid Coloumn C".

The other way I can think around is to declare another entity ex:ListEntity2 and add the values after query from ListEnity which I guess is a good way but just wanted to know of any other possibilities.

table.cs:

 [Table("List")]
    public class ListEntity
    {
        [Key]
        public int ID { get; set; }
        public string A { get; set; }
        public int B { get; set; }
        private string name;
        public virtual string C
        {
            get 
            {
                return name;
            }
            set
            {
               name=value ;
            }
        }
    }

dbcontext.cs:

public DbSet<ListEntity> List { get; set; }
sss111
  • 349
  • 1
  • 7
  • 27
  • 1
    See [Ignoring a class property in Entity Framework 4.1 Code First](http://stackoverflow.com/questions/10385248/ignoring-a-class-property-in-entity-framework-4-1-code-first), or consider using your entity models only as entity models and implement any alterations through inheritance, composition or extension methods. – CodeCaster Jun 15 '15 at 20:03

1 Answers1

3

You can try using the NotMapped attribute (Documentation)

[...] Denotes that a property or class should be excluded from database mapping.

For example:

using System.ComponentModel.DataAnnotations.Schema;

[Table("List")]
public class ListEntity
{
    [Key]
    public int ID { get; set; }
    public string A { get; set; }
    public int B { get; set; }

    private string name;

    [NotMapped]
    public string C
    {
        get { return name; }
        set { name = value; }
    }
}
Matias Cicero
  • 25,439
  • 13
  • 82
  • 154