コードファーストの命名規則に従わない多対多の関係を持つ2つのエンティティがあり、それをオーバーライドする方法を見つける必要があります。
最初のエンティティ:
public class User
{
public int UserId { get; set; }
public string Username { get; set; }
public virtual ICollection<Rule> { get; set; }
}
2番目のエンティティ:
public class Rule
{
public int RuleId { get; set; }
public string Description { get; set; }
public virtual ICollection<User> { get; set; }
}
これら2つの間に、従来のマッピングを使用したテーブルがあります(名前は、対応する外部キーを持つ2つの列()でUserRule
構成される複合主キーを使用しています)UserId, RuleId
私が使用するdbcontextはこれです:
public class DataContext : DbContext
{
public IDbSet<User> Users { get; private set; }
public IDbSet<Rule> Rules { get; private set; }
private const string ConnectionStringName = "connectionstring";
public DataContext() : base(ConnectionStringName)
{
Configuration.LazyLoadingEnabled = true;
Rules = Set<Rule>();
Users = Set<User>();
}
protected override void OnModelCreating(DbModelBuilder builder)
{
// use this to disable database migrations and not use metadata inside database
Database.SetInitializer<DataContext>(null);
// setup MaestroAgentConfig to its table
builder.Configurations.Add(new UserTable());
// setup SecurityRule to its table
builder.Configurations.Add(new RuleTable());
base.OnModelCreating(builder);
}
public override int SaveChanges()
{
return base.SaveChanges();
}
}
私が持っているマッピングテーブルは次のとおりです。
public class UserTable : EntityTypeConfiguration<User>
{
public UserProfileTable()
{
Property(x => x.UserId).HasColumnName("UserId").HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
HasMany(x => x.SecurityRules)
.WithMany(x => x.UserProfiles)
.Map(map =>
{
map.MapRightKey("UserId");
map.MapRightKey("RuleId");
map.ToTable("UserRule");
});
ToTable("User");
}
}
と :
public class RuleTable : EntityTypeConfiguration<Rule>
{
public RuleTable()
{
Property(x => x.RuleId).HasColumnName("RuleId").HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
HasKey(x => x.RuleId);
ToTable("Rule");
}
}
しかし、EFがDBにクエリを実行すると、次のようになります。
exec sp_executesql N'
SELECT TOP (1)
[Extent1].[UserId] AS [UserId],
{ other fields }
FROM
[dbo].[UserProfile] AS [Extent1]
WHERE
[Extent1].[UserName] = @p__linq__0',N'@p__linq__0 nvarchar(4000)',@p__linq__0=N'EMYODE\erick.girard'
と :
exec sp_executesql N'
SELECT
[Extent2].[RuleId] AS [RuleId],
[Extent2].[Description] AS [Description]
FROM
[dbo].[UserRule] AS [Extent1]
INNER JOIN
[dbo].[Rule] AS [Extent2] ON [Extent1].[RuleId] = [Extent2].[RuleId]
WHERE
[Extent1].[User_UserId] = @EntityKeyValue1',N'@EntityKeyValue1 int',@EntityKeyValue1=37
2回目のリクエストで、テーブルUserId
だけで「」を使用する方法が見つかりません。UserRule
どうすればこれを行うことができますか?
(編集)次の3つの規則を削除しようとしましたが、これまでのところ何も変更されていません。
builder.Conventions.Remove<PluralizingEntitySetNameConvention>();
builder.Conventions.Remove<NavigationPropertyNameForeignKeyDiscoveryConvention>();
builder.Conventions.Remove<TypeNameForeignKeyDiscoveryConvention>();