Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I include an unmapped field in a POCO class

I'm new to the EF and am just experimenting. Can someone tell me if the following is possible. Given a (product) table in the DB like so:

Id Cost DescriptionFK
-- ---- -------------
?  ?    ?

I want the corresponding POCO class (entity) to appear like:

public class Product
{
    public int Id { get; set; }
    public decimal Cost { get; set; }
    public string Description { get; }
}

Note that the "Description" in the class is a read-only string (no setter), but it's a key in the table. I'm calling a stored procedure to pull this off (converting the key to its corresponding string and returning the above class), but if I now do something like:

// ...
product.Cost = 20;
myContext.SaveChanges();

I get an exception complaining that there's no mapping for the "Description" string. I removed the mapping because it's read-only and I don't need to include the "DescriptionFK" in the class itself. Is there some way to pull this off (POCO only). Thanks very much.

like image 371
John Brown Avatar asked Jul 28 '12 14:07

John Brown


People also ask

How do we express that an attribute is not mapped to a column?

The [NotMapped] attribute overrides this default convention. You can apply the [NotMapped] attribute on one or more properties for which you do NOT want to create a corresponding column in a database table. In the above example, the [NotMapped] attribute is applied to the Age property of the Student class.

What is NotMapped attribute in MVC?

The NotMapped attribute is used to specify that an entity or property is not to be mapped to a table or column in the database. In the following example, the AuditLog class will not be mapped to a table in the database: public class Contact.

Which method is used to apply configuration to entities or their properties in the entity framework Core?

Property Mapping. The Property method is used to configure attributes for each property belonging to an entity or complex type.


1 Answers

If you are just looking to have the Description property as a calculated field, add [NotMapped] to your the property to explicitly exclude it and then generate the database:

public class Product
{
    public int Id { get; set; }
    public decimal Cost { get; set; }

    [NotMapped] 
    public string Description { get; }
}
like image 130
Judo Avatar answered Oct 03 '22 00:10

Judo