0

私はユーザーとクライアントの間に多対多の関係を持っています。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]}
]
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 に答える