简体   繁体   中英

Is there a way to fill navigation properties without saving an entity to the database?

Let's say I have an entity PersonEntity with a property EyeColorId and navigation property of type EyeColorEntity . Is there a way to prefetch the EyeColorEntity without saving the entity and without just querying for the EyeColor .

Ex.

public class PersonEntity
{
    public int Id { get; set; }
    public int EyeColorId { get; set; }
    public EyeColorEntity EyeColor { get; set; }
}

public void FillFromDbExample(DbContext context)
{
    var personEntity = new PersonEntity()
    {
        EyeColorId = 5
    };
    context.SetNavigationProperties(personEntity);
}

Theoretically this would fill the navigation property on the entity. The result would look something like this.

personEntity =
{
    EyeColorId = 5,
    EyeColor =
    {
        Id = 5,
        Color = "Blue"
    }
}

The trick here is that I don't want to have to individually query for each property and I don't want to have to save the entity to the database to pull these properties back. Does something like the described functionality exist in EnityFramework 6.2.0.

You can pre-load all properties in the context to make relationship fixup work. For example:

context.EyeColors.Load();
var personEntity = new PersonEntity()
{
    EyeColorId = 5
};
context.Persons.Attach(personEntity);

In the last statement EF automatically populated personEntity.EyeColor .

Alternatively, you can rely on lazy loading by initializing the entity as a lazy-loading proxy. The property must be virtual to enable proxy creation:

public virtual EyeColorEntity EyeColor { get; set; }

Then:

var personEntity = context.Persons.Create(); // Creates a proxy
personEntity.EyeColorId = 5;
context.Persons.Attach(personEntity);

Now EF will query the matching EyeColor from the database when personEntity.EyeColor is accessed (= lazy loading).

I don't want to have to individually query for each property

Lazy loading does query properties individually, but it's not you who has to do it.

Note that in both cases personEntity must be attached to the context.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM