0

So I'm building a base library, let's call it A, which has a number of simple classes. That library should not use the Entity Framework reference because you can work with these objects without using a database at all.

Then I have another library called A.EntityFramework which should add the ability to use Entity Framework to put those objects into a database.

My problem is that to be able to use them with Entity Framework I need the attributes [Key], [Index] etc on the class definitions in the base library. But those attributes are defined in Entity Framework which that library doesn't reference...

What is the proper way to solve this situation?

CodeOrElse
  • 328
  • 2
  • 16
  • 1
    Keep entity objects to Entity Framework, and map then to separate domain objects. Don't tie your data model that hard to your domain model. Also try searching. Or if you insist, use [fluent mapping in your DbContext ModelCreating()](https://stackoverflow.com/questions/21018067/entity-framework-code-first-model-separation-from-domain). – CodeCaster Sep 19 '17 at 11:58
  • Possible duplicate of [Deriving a database model for view model in ASP.MVC](https://stackoverflow.com/questions/46190851/deriving-a-database-model-for-view-model-in-asp-mvc) – Sefe Sep 19 '17 at 12:12
  • CodeCaster, normally I would agree with you, in this case though I just need to add the objects and SaveChanges, that's all, so it felt wasteful performance-wise to map them to another object and save that. Fluent mapping in OnModelCreating() seems like the way to go for me. Thanks! – CodeOrElse Sep 19 '17 at 18:47

1 Answers1

3

You can define those properties in OnModelCreating method of your DbContext class.

For example:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    base.OnModelCreating(modelBuilder);

    //Class1
    modelBuilder.Entity<A.Class1>.HasKey(p => p.ID);
    modelBuilder.Entity<A.Class1>.Property(p => p.Field1).IsRequired().HasMaxLength(50);

    //Class2
    modelBuilder.Entity<A.Class2>.HasKey(p => new {
        p.Key1,
        p.Key2
    });
    modelBuilder.Entity<A.Class2>.Property(p => p.Key1).IsRequired().HasColumnOrder(1);
    modelBuilder.Entity<A.Class2>.Property(p => p.Key2).IsRequired().HasColumnOrder(2);
}

You can learn more about Entity Framework Fluent API here.

Chan MT
  • 495
  • 4
  • 9