I have a lot of interconnected objects in the project I'm working on, and I use WCF to use them in several client applications. Soon I realized that with every call, I serialized half the data in the database. I fixed the immediate problem, but the system still processes a lot of database queries, since service-level objects repeat all nested objects in the data layer in their constructors. Many times this is completely unnecessary, so I began to consider alternatives.
If I specify the identifier of my attached property, I do not believe that the database call will be executed unless I get access to the properties of the attached object.
public class MyDataObject
{
public Guid Id { get; set; }
public string SomeProperty { get; set; }
public Guid NestedDataObjectId { get; set; }
[ForeignKey("NestedDataObjectId")]
public virtual NestedDataObject NestedDataObject { get; set; }
}
Then I can use the constructor of my service object to determine whether it is lazy to load nested objects like this:
public class MyServiceObject
{
public MyServiceObject(MyDataObject myDataObject,
bool includeNested = true)
{
Id = myDataObject.Id;
SomeProperty = myDataObject.SomeProperty;
NestedServiceObjectId = myDataObject.NestedDataObjectId;
if (includeNested)
NestedServiceObject = new NestedServiceObject(myDataObject.NestedDataObject,
includeNested);
}
}
Which works fine, except that now I have a problem with my db mock context for my unit tests, since I have to add an object and id to each mock DbSet
when I change the service code to use a NestedObjectId
property, not a propertyNestedObject.Id
Therefore, I was wondering if the Id field is the only virtual property available to me if it still calls the database for the entire object. Sort of
if (includeNested)
{
NestedServiceObject = new NestedServiceObject(myDataObject.NestedDataObject);
}
else
{
NestedServiceObject = new NestedServiceObject(myDataObject.NestedDataObject.Id);
}
, NestedObject.Id
, , , , , , .