0

I'm using Entity Framework 6 in my C# Project. When I have a Model class with let's say 20 properties but I only want to write 2 of these Properties in to my Database, is there a way to exclude all but say I want these 2 to be mapped. Small example here:

public class Blog
{
    public int BlogId { get; set; }

    [NotMapped]
    public string Url { get; set; }

    [NotMapped]
    public DateTime LoadedFromDatabase { get; set; }
}

I want only my BlogId to be written into the Database, which means I would need to write [NotMapped] for every other property in the class. Which also means when I add 10 properties, I need to write [NotMapped] for every single property which can take some time.

Is there a way to make this easier, so for example something like "ignore all except specified properties"?

JPocoata
  • 634
  • 1
  • 11
  • 24
Markus
  • 1
  • 1
  • 1
    Possible duplicate of [Ignoring all properties but some in Entity Framework 6](https://stackoverflow.com/questions/31066906/ignoring-all-properties-but-some-in-entity-framework-6) – Sani Huttunen Sep 27 '18 at 12:00
  • You can extend the EF class and add your extra fields in the extended while reading and writing the base class fields. – Ross Bush Sep 27 '18 at 12:01
  • 1
    Why are you adding so many un-mapped properties to your entity? I'd suggest finding an approach where your entities represent the data in the DB and then map them to other objects that can have the additional properties. – juharr Sep 27 '18 at 12:01
  • Agree with the above. In small cases just extend the partial class generated by the EF designer when you want extra fields that are not stored in the database. I use this when I have a user ID but the name is in UserIdentity. You can also use a stored procedure to get or add records that don't fit easily into the usual table/view scenario. Remember that any value that are allowed null in your table can be ignored for insert and update anyway - just don't set them on update –  Sep 27 '18 at 13:09

0 Answers0