0

I try to implement 1..0 relations with Entity Framework 6. I use instance associsaltion. I try to repeat the examples from web and forums but somehow it doesn't work for me. Please, help.

Entities:

  public class CustomerWithFk : Item  // Item contains Id
    {
        public string Name { get; protected set; }
        public virtual City City { get; set; }      // relation property. Can be 1 or 0
        public virtual Product Product { get; set; }
        public decimal Money { get; protected set; }
    }

    public class City : Item
    {
        public string Name { get; protected set; }
    }

Mappings:

public CityMap()
{
    ToTable("Cities");
    HasKey(c => c.Id);
}

public CustomerFkAssosiationMap()
{
    ToTable("Customers");
    HasKey(c => c.Id);

    HasRequired(g => g.City)
        .WithRequiredDependent();

    HasRequired(g => g.Product)
                .WithRequiredDependent()
                .Map(x => x.MapKey("ProductId"));
}

Database tables: enter image description here

SQL Profiler gives me enxt SQL request:

SELECT 
    1 AS [C1], 
    [Extent1].[Id] AS [Id], 
    [Extent1].[Name] AS [Name], 
    [Extent1].[Money] AS [Money], 
    [Extent1].[CityId] AS [CityId], 
    [Extent1].[ProductId] AS [ProductId]
    FROM [dbo].[Customers] AS [Extent1]

So, I don't see any joins here to load data from Cities or Products. And the result is Null: enter image description here

I tried different mapping options, like: HasOptional, WithRequiredPrincipal, tried to add Customers proeprty to City (while it's incorrect and City doesn't have to know something about customers) Nothing helps. The assosiated entities are always null. Where am I wrong?

Artem A
  • 2,154
  • 2
  • 23
  • 30

1 Answers1

1

The problem is that you are not including the related objects. Try something like this using Include:

var list = context.CustomerWithFk
                  .Include("City")
                  .Include("Product");

That tells Entity Framework that you want to pull back the customer along with the city and product. Here is some further reading if you are interested: http://msdn.microsoft.com/en-us/data/jj574232.aspx.

EDIT: You could also enable lazy loading (based on your comment I believe it is what you are after) by adding this to your context:

context.ContextOptions.LazyLoadingEnabled = true;

Read more about lazy loading here: http://msdn.microsoft.com/en-us/library/vstudio/dd456846(v=vs.100).aspx.

Dean
  • 2,084
  • 17
  • 23
  • Thanks. But is there any way not to use explicit command like Include and loed by FK in background? I'm sure, that yesterday, during some experiments with mapping I got the correct result with filled properties without calling Include. It looks like I'm woking very close to solution, but blind and can't see my mistakes... – Artem A Dec 13 '14 at 18:59
  • 1
    See edit. I believe you are looking for lazy loading. – Dean Dec 13 '14 at 20:05