Can EF Core be configured to ignore a child property when saving, create the relationship with a foreign key, but still populate child on retrieval?

Viewed 113

I have a parent object that sets a child property with its foreign key to prevent duplication of the child in the database.

public class Unit
{
   public Unit(UnitType unitType)
   {
      unitTypeCode = unitType.Id;
   }

   public UnitType UnitType {get; private set;}
   private int unitTypeCode;
}

public class UnitType
{
    public static UnitType  Campus => new UnitType(1, nameof(Campus));
    private UnitType(int id, string name)
    { ... }
    public int Id {get; private set;}
    public string Name {get;private set;}
}

This is sufficient for the application as the unit will always be retrieved through the DbContext before any further operations are done on it. The issue is when writing unit tests for this object, I am not using EF Core to test which is resulting in my UnitType property not being set.

[TestMethod]
public void Can_Set_Campus()
{
     var unit = new Unit(UnitType.Campus);

     // this will be false because unit.UnitType is never set
     Assert.IsTrue(unit.UnitType == UnitType.Campus); 
}

Is there a way to set the UnitType and have EF Core ignore it when saving (using the foreign key to create the relationship) but still populate the related property when retrieving the data?

Alternatively, is there a better way to handle testing for this type of situation?

Update: more info on UnitType structure per Felipe's comment: There are 3 'UnitTypes' that can be assigned to a Unit:

Id Name
1 Campus
2 Building
3 Room

I am creating a new object each time, which is why I am using the foreign key to create the relationship in EF Core (to avoid creating the duplicate that EF by default creates when the object is populated). Ultimately is there a way to tell EF "Don't create a record for the UnitType when saving, just add the _unitTypeId for foreign key reference"?

I know I could retrieve the UnitType from the DB every time, so it's already being tracked by EF, but I would prefer to not to have to do this. I'd like to keep only aggregate roots exposed in the DbContext.

We are managing status indicators in a similar way, so this issue manifests itself in multiple ways.

0 Answers
Related