Reputation: 21449
In my application, I have two EF entities, a User and a Company. These two entites have a 1 to 1 relationship.
public class Company : IEntity
{
public virtual int Id { get; set; }
[Required]
public virtual User Owner { get; set; }
public virtual String Name { get; set; }
public virtual String Address { get; set; }
public virtual byte[] Logo { get; set; }
}
And a user:
public class User : IEntity
{
[NotMapped]
public virtual int Id { get; private set; }
[Key]
[Required]
public virtual string Email { get; set; }
public String Name { get; set; }
public virtual Company Company { get; set; }
}
I query these objects with the following Breeze js code:
var query = EntityQuery.from('CurrentUser').expand('Company');
The web api controller has these two methods:
[HttpGet]
public IQueryable<User> CurrentUser()
{
var userName = ...
return _breezeContext.Context.Users.Find(sup => sup.Email.Equals(userName)).AsQueryable();
}
[HttpGet]
public IQueryable<Company> Company()
{
var userName = ...
return _breezeContext.Context.Companies.Find(cmp => cmp.Owner.Email.Equals(userName)).AsQueryable();
}
I can clearly see this coming back from the server:
{$id:1, $type:User, MyNamespace, Id:0, Email:[email protected],…}
$id: "1"
$type: "MyNamespace.Models.User, MyNamespace"
Company: {$id:2, $type:MyNamespace.Models.Company, MyNamespace, Id:1, Owner:{$ref:1}, Name:My Company,…}
$id: "2"
$type: "MyNamespace.Models.Company, MyNamespace"
Address: "somewhere in the world"
Id: 1
Logo: {$type:System.Byte[], mscorlib,…}
Name: "company"
Owner: {$ref:1}
Email: "[email protected]"
Id: 0
Name: "Operator 2"
Now in my js code, I can correctly see the User
object but not the Company
. User.company is also undefined
QUESTION
1. What is wrong with my code above and why does Breeze not deserialize my objects correctly?
2. How can I get my object graph to build correctly on the client side so that I can bind my user interface elements to user
and user.company
properties?
I went through all the Breeze samples with no luck - any help is really appreciated
Upvotes: 1
Views: 259
Reputation: 526
In an EF one-to-one relation, the FKs will also have to be the PKs, so you shouldn't be using Email as User PK.
Even if what you are doing (i.e. not using the PKs as FKs) was possible, you would still have problems as you marked your FK in User as unmapped.
Breeze associations require foreign keys and if you don't have that information in the DB, it's not possible for Breeze to resolve the relation.
So I suggest you set Id in User and the PK and set Email as unique. For the latter you might want to check Unique Constraint in Entity Framework Code First.
Upvotes: 2