我在用户和客户之间有一个多对多的关系。我将 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]}
]