私はユーザーとクライアントの間に多対多の関係を持っています。FluentAPIでEF5コードファーストを使用しています。私のエンティティは次のようになります。
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を使用してこれを構成するにはどうすればよいですか?
または、リレーションシップのIDのみをシリアル化するようにJSONシリアライザーを構成できれば同様に満足します。このようなもの:
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]}
]