简体   繁体   中英

How to extend entity class?

I'm using Entity Framework and Mysql. And I have Entity classes for each tables.

But I do not know how to extend fields into entity class that does not defined in DB .

For example) I have test table and the table have id, price and qty fields.

My entity class is like this,

[Table('test')]
public class Test
{
  [Key]
  public int id {get; set;}
  public decimal price {get; set;}
  public int qty {get; set;}
}

Now, I need subtotal field in Test class. (for some reason, I can not modify DB )

so I try to make the Test class as Partial class,

[Table('test')]
public partial class Test
{
  [Key]
  public int id {get; set;}
  public decimal price {get; set;}
  public int qty {get; set;}
}

public partial class Test 
{
  public decimal? subTotal {get; set;}
}

Then I got an error : It say, 'Unknown column 'Extent1.subTotal' in 'field list''

Anybody know, How can I add the subTotal field into Test class without changing DB structure?

Please advice me.

Use the NotMappedAttribute for any properties you want to have in your model, but do not want Entity Framework to map to your database.

 [Table('test')]
    public class Test
    {
      [Key]
      public int id {get; set;}
      public decimal price {get; set;}
      public int qty {get; set;}
      [NotMapped]
      public decimal? subTotal {get; set;}
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM