0
我有兩個實體,其中多對多關係不遵循代碼優先的命名約定,我必須找到一種方法來覆蓋該關係。替代多對多關係的代碼優先命名約定
第一實體:
public class User
{
public int UserId { get; set; }
public string Username { get; set; }
public virtual ICollection<Rule> { get; set; }
}
第二實體:
public class Rule
{
public int RuleId { get; set; }
public string Description { get; set; }
public virtual ICollection<User> { get; set; }
}
我有一個表中的那些2與經典的映射(名稱是UserRule
具有由2個colums複合主鍵的間(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查詢數據庫,它看起來像這樣:
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>();
哦,我的......今天我是多麼的愚蠢......修復它! – Erick 2012-08-02 20:14:20