Reputation: 1274
Below is an example code which should demonstrate what I'm trying to achieve:
public static void addRecord(CargoShip ship, DbContext db)
{
// Realistically, in my application this is decided by business logic, - omitted for brevity
long containerTypeIDNewContainer = 5;
Container containerToAdd = new Container()
{
cargoShipBelongingToID = ship.cargoShipID,
containerTypeID = containerTypeIDNewContainer
};
ship.Containers.Add(containerToAdd);
// This line of code is what I want to be able to do
// WITHOUT doing a db.SaveChanges
// ContainerType is a lookup table in the database, each container type has pre-defined
// Height/Width etc
// This throws a null exception, ContainerType object does not exist.
string containerHeight = containerToAdd.ContainerType.Height;
}
I basically want to be able to create a new Container
and fill in a foreign key on that object, and be able to access the child of the foreign key as an object in code.
if I call a SaveChanges, it will naturally go and fetch the values for the Container object, but I want to fill in those values/objects without having to do a Savechanges.
edit:
Forgot to mention incase it is not clear. The relationship is: CargoShip
has many Container
, a Container
has ONE ContainerType
, which is a FK and is non nullable.
Can you help with this.
Thanks
Upvotes: 0
Views: 127
Reputation: 27526
EF will not fill in all your FK properties for you just because you set an ID in your entity. Those properties will only be set after you call SaveChanges
.
For that reason, there's not much point in calling Add
unless you do actually intend to call SaveChanges
at some point.
If you simply want to get the appropriate ContainerType
, then you may as well do a Select
(or Find
) - which ultimately boils down to much the same SQL query that EF would have to use behind the scenes anyway:
var containerType = db.ContainerTypes.Find(containerTypeIdNewContainer);
Note that the Find
method will only go to the DB if the particular containerType
record does not already exist in the local cache. However, the lifetime of the local cache is tied to the lifetime of the DbContext
, so may be very short.
It may make sense to maintain your own cache of commonly-used entities like this if they're relatively stable:
var containerTypes = db.ContainerTypes.ToDictionary(x => x.Id, x => x);
...
var containerType = containerTypes[containerTypeIdNewContainer];
Upvotes: 1
Reputation: 87
Assuming you can access your DbContext (not familiar with EntityFrameworkConnection class) then you can simply use an IQueryable.
IQueryable<T> query = db.Set<ContainerType>()
var containerType = query.FirstOrDefault(x => x.containerTypeID == containerTypeIDNewContainer)
string containerHeight = containerType.Height;
Hope I understood your question properly
Upvotes: 0