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.
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.
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.
Property Mapping. The Property method is used to configure attributes for each property belonging to an entity or complex type.
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; }
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With