EF, Code First, WCF => problem with empty collection

I'm having some problems with the first version of Ef 4.1 code.

public class Foo()
{
    public Foo()
    {
        Id = Guid.NewGuid();
        Bars = new Collection<Bar>();
    }

    public Guid Id { get; set; }
    public string Name { get; set; }
    public virtual ICollection Bars { get; set; }
}

public class Bar()
{
    public Bar()
    {
        Id = Guid.NewGuid();
    }

    public Guid Id { get; set; }
    public string Name { get; set; }
    public virtual Foo Foo { get; set;}
}

public class MyContext : DbContext
{
    public MyContext()
    {
        Configuration.ProxyCreationEnabled = false;
    }

    public DbSet<Foo> Foos { get; set; }
    public DbSet<Bar> Bars { get; set; }
}

When I put a wcf service on top of this, it returns only an empty collection of bars. If I enable ProxyCreationEnabled, the collection will be populated, but then I will get wcf exceptions and closed connections due to the creation of an EF proxy.

Any suggestions?

+3
source share
1 answer

, . EF . EF , . -, EF Bars ( ), - , - (Bar.Foo Foo.Bars ).

, Include :

var data = context.Foos.Include(f => f.Bars).ToList();

, Foo Bar, Foo Bar DataContract IsReference=true DataMember:

[DataContract(IsReference=true)]
public class Foo()
{
    public Foo()
    {
        Id = Guid.NewGuid();
        Bars = new Collection<Bar>();
    }

    [DataMember]
    public Guid Id { get; set; }
    [DataMember]
    public string Name { get; set; }
    [DataMember]
    public virtual ICollection Bars { get; set; }
}

[DataContract(IsReference=true)]
public class Bar()
{
    public Bar()
    {
        Id = Guid.NewGuid();
    }

    [DataMember]
    public Guid Id { get; set; }
    [DataMember]
    public string Name { get; set; }
    [DataMember]
    public virtual Foo Foo { get; set;}
}

Foo Bar :

public class Bar()
{
    public Bar()
    {
        Id = Guid.NewGuid();
    }

    public Guid Id { get; set; }
    public string Name { get; set; }
    [IgnoreDataMember]
    public virtual Foo Foo { get; set;}
}
+6

All Articles