0

我在用户和客户之间有一个多对多的关系。我将 EF 5 Code First 与 Fluent API 一起使用。我的实体如下所示:

public class UserProfile 
{
    public int Id { get; set; }
    public virtual Collection<Client> Clients { get; set; }
}

public class Client
{
    public int Id { get; set; }
    public virtual Collection<UserProfile> Users { get; set; }
}

在我的 UserProfile 配置类中有以下流利的 API 来声明关系:

HasMany(u => u.Clients)
    .WithMany(c => c.Users)
    .Map(m => m.MapLeftKey("UserId").MapRightKey("ClientId").ToTable("ClientUsers"));

所有这一切都完美无缺,我的 Join 表就像您期望的那样创建。

我的问题是这些实体被序列化为 JSON 并且它们之间的循环依赖会导致问题。我希望做的是序列化客户或用户的 ID 列表。像这样的东西:

public class UserProfile 
{
    public int Id { get; set; }
    public virtual Collection<int> ClientIds { get; set; }

    [JsonIgnore]
    public virtual Collection<Client> Clients { get; set; }
}

public class Client
{
    public int Id { get; set; }
    public virtual Collection<int> UserIds { get; set; }

    [JsonIgnore]
    public virtual Collection<UserProfile> Users { get; set; }
}

如何使用 Fluent API 进行配置?

或者,如果我可以将 JSON 序列化程序配置为仅序列化关系的 ID,我会同样高兴。像这样的东西:

public class UserProfile 
{
    public int Id { get; set; }

    [SomeAnnotation to make it only output the ID of each client]
    public virtual Collection<Client> Clients { get; set; }
}

public class Client
{
    public int Id { get; set; }

    [SomeAnnotation to make it only output the ID of each user]
    public virtual Collection<UserProfile> Users { get; set; }
}

最后,我希望我的序列化 JSON 看起来像这样:

List of all users:
[
  {"userId": 1, "clientIds": [1,2]},
  {"userId": 2, "clientIds": [2,3]}
]

List of all clients:
[
  {"clientId": 1, "userIds": [1]},
  {"clientId": 2, "userIds": [1,2]},
  {"clientId": 3, "userIds": [2]}
]
4

2 回答 2

0

您无法使用流畅的 API 来实现这一点 - 这是您的序列化问题,而不是映射问题。您的映射按原样正确。您必须在不更改映射的情况下解决序列化问题 - 它可能涉及创建从映射类型投影的新 DTO 类型,然后这些类型将被正确序列化。

于 2013-02-08T09:22:06.260 回答
0

我想出了一个可行的解决方案,它给了我想要的东西。我很好奇社区是否认为这是一个好模式......

public class UserProfile 
{
    public int Id { get; set; }

    [JsonIgnore]
    public virtual Collection<Client> Clients { get; set; }

    public ICollection<int> ClientIds
    {
        get
        {
            return this.Clients == null ? null : this.Clients.Select(c => c.Id).ToList();
        }
    }
}

public class Client
{
    public int Id { get; set; }

    [JsonIgnore]
    public virtual Collection<UserProfile> Users { get; set; }

    public ICollection<int> UserIds
    {
        get
        {
            return this.Users == null ? null : this.Users.Select(c => c.Id).ToList();
        }
    }
}

然后在我的 FluentAPI 配置中

User Configuration:
Ignore(u => u.ClientIds);

Client Configuration:
Ignore(c => c.UserIds);
于 2013-02-08T14:19:59.297 回答