2

这是我的模型。

    public class User
{
    public string Id { get; set; }
    public string Username { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Password { get; set; }
    public string Headline { get; set; }
    public virtual ICollection<Address> Addresses { get; set; }
    public virtual ICollection<Phonenumber> Phonenumbers { get; set; }
    public virtual ICollection<Email> Emails { get; set; }
    public virtual ICollection<Position> Positions { get; set; }
}

这是 GET 方法。

    // GET api/App
    public IEnumerable<User> GetUsers()
    {
        db.Configuration.ProxyCreationEnabled = false;
        return db.Users.AsEnumerable();
    }

我已禁用代理创建,因为显然实体框架和序列化存在某种问题。

当我转到 localhost:12345/api/App/ 时,它返回以下 JSON 对象。您会注意到 Addresses 字段和 Positions 的所有路径都显示为空。

[{"$id":"1","Id":"1","Username":"Bob","FirstName":"Foo","LastName":"Bar","Password":"123","Headline":"Something","Addresses":null,"Phonenumbers":null,"Emails":null,"Positions":null}]

但是我不明白为什么它是空的,因为它曾经显示它们。当我转到显示的 localhost:12345/api/App/1 时,我可以确认它在那里,数据:

{"$id":"1","Addresses":[{"$id":"2","Id":"3","Uaddress":"Test address","Country":"Fantasy Land","Zipcode":"0000","Cycle":0,"UserId":"3","User":{"$ref":"1"}}],"Phonenumbers":[{"$id":"3","Id":"2","Number":"12345678","Cycle":0,"UserId":"3","User":{"$ref":"1"}}],"Emails":[{"$id":"4","Id":"2","Uemail":"bob@example.com","Cycle":0,"UserId":"3","User":{"$ref":"1"}}],"Positions":[{"$id":"5","Company":{"$id":"6","Id":"2","Name":"Bobs ApS","Type":"Bobs","Industry":"Magic","Size":"1337"},"Id":"2","Title":"CEO","Iscurrent":true,"CompanyId":"2","UserId":"1","User":{"$ref":"1"}}],"Id":"1","Username":"bob","FirstName":"Foo","LastName":"Bar","Password":"1234","Headline":"Something"}

正如您将看到的那样,该字段都填写了数据。任何想法为什么当我尝试获取所有用户时它没有显示?

4

1 回答 1

3

现在您已禁用代理,延迟加载不会为您获取子实体。您需要专门询问他们:

return db.Users.Include(x => x.Addresses).Include(x => x.Positions).AsEnumerable();
于 2013-04-12T13:44:06.430 回答