5

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.

John Brown
  • 131
  • 2
  • 7

2 Answers2

15

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; }
}
Judo
  • 5,167
  • 3
  • 24
  • 34
0

AFAIU, it is not possible.

"You always need at least one navigation property to create a foreign key constraint in the database."

EF Code First foreign key without navigation property

Dojo
  • 59
  • 1
  • 7