2017-01-27 2 views
0
public static void RegisterMappings() 
     { 
      BsonClassMap.RegisterClassMap<Job>(map => 
      { 
       map.AutoMap(); 
       map.IdMemberMap.SetIdGenerator(StringObjectIdGenerator.Instance); 
      }); 

      BsonClassMap.RegisterClassMap<JobRun>(map => 
      { 
       map.AutoMap(); 
       map.IdMemberMap.SetIdGenerator(StringObjectIdGenerator.Instance); 
      }); 
     } 

私のプロジェクトのすべてのクラスで、私はIdプロパティを持っています。私はすべてのクラスのidgeneratorを設定する必要があります。どのようにコードの反復を避けるために?c#mongodbのすべてのクラスに対してsetIdGeneratorの繰り返しを避けるにはどうすればいいですか?

答えて

0

あなたがそれを登録する必要がありますすべてのクラスの例インターフェイスISetIdGeneratorのために定義されている場合、あなたは次の手順を実行できます。

var types = Assembly.GetExecutingAssembly().ExportedTypes 
      .Where(x=>x.GetInterfaces().Contains(typeof(ISetIdGenerator))); 

foreach (var type in types) 
{ 
    var classMap = new BsonClassMap(type); 
    classMap.AutoMap(); 
    classMap.IdMemberMap.SetIdGenerator(StringObjectIdGenerator.Instance); 
    BsonClassMap.RegisterClassMap(classMap); 
} 

確かに、あなたはこのインタフェースを回避し、溶液中のすべてのクラスのマッパーを登録することができますが、私それは少しオーバーヘッドだと思う。

0

IClassMapConventionを作成して登録することができます。

public class IdGeneratorClassMapConvention : ConventionBase, IClassMapConvention 
{ 
    public void Apply(BsonClassMap classMap) 
    { 
      map.AutoMap(); 
      map.IdMemberMap.SetIdGenerator(StringObjectIdGenerator.Instance); 
    } 
} 

と。これは、すべての非列挙型の型に適用されます

 ConventionRegistry.Register("IdGeneratorConvention", new ConventionPack 
     { 
      new IdGeneratorClassMapConvention() 
     }, t => !t.GetTypeInfo().IsEnum); 

それを登録します。それでもBsonClassMap.RegisterClassMap<T>() iircに電話する必要があります。 2番目のパラメータt => !t.GetTypeInfo().IsEnumは、タイプを制限するフィルタです。

関連する問題