mercredi 8 novembre 2017

WPF Load collection with rest of foreign keys even if one is null or 0

Note: I'm using EF6, and MahApps.Metro

I'm getting an error injecting ForeignKey objects into the class that has them (properly) annotated.

Let's say I have a model

public class Image : ObservableObject
{
    private Type _type;
    private int _typeId;
    private Code _code;
    private int _codeId;

    [ForeignKey("TypeId")]
    public virtual Type Type 
    {
        get => _type;
        set => Set(()=> Type, ref _type, value);
    }

    public int TypeId
    {
       get => _typeId;
       set => Set(()=> TypeId, ref _typeId, value);
    }   

    [ForeignKey("CodeId")]
    public virtual Code Code
    {
        get => _code;
        set => Set(()=> Code , ref _code, value);
    }

    public int CodeId
    {
       get => _codeId;
       set => Set(()=> CodeId, ref _codeId, value);
    }
}

And a repository method :

public async Task<IEnumerable<Image>> GetAll()
{
    using (var context = new DatabaseContext())
    {
        return await context.Images.ToListAsync();
    }
}

If I use this method of retrieving database objects, debugging my model shows that all of the ForeignKey objects throw a System.ObjectDisposedException.

The reason (I think) this happens is due to me not adding .Including(image => image.Code).Include(image => image.Type) to the return statement.

Why I'm not adding is due to the fact that sometimes the Image class contains Code, but sometimes it doesn't. If I try to load list of Images with .Include and class doesn't have a Code, the repository returns an empty list.

So is there a way to not add .Include() methods but have the context ignore the "unexistant" foreign keys?

I'd love any advice over my repository and model design. (probably a question for stack exchange)

Aucun commentaire:

Enregistrer un commentaire