我有一个现有的数据库,它包含下面这两个表:
我正在尝试使用流利的映射从头开始使用数据库创建 EF Code First。
我配置了以下 dbContext:
public partial class EFContext : DbContext
{
public EFContext()
: base("name=DbContext")
{
}
public virtual DbSet<Users> Users { get; set; }
public virtual DbSet<Log> Log { get; set; }
public virtual DbSet<Token> Tokens { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Configurations.Add(new UserConfiguration());
modelBuilder.Configurations.Add(new LogConfiguration());
modelBuilder.Configurations.Add(new TokenConfiguration());
}
}
public partial class Users
{
public int UserId { get; set; }
public string Username { get; set; }
public string Password { get; set; }
public int Active { get; set; }
public DateTime RegDate { get; set; }
public virtual Token Token { get; set; }
}
public class Token
{
public string TokenId { get; set; }
public int UserId { get; set; }
public string TokenValue { get; set; }
public int Active { get; set; }
public DateTime Fecalt { get; set; }
public virtual Users User { get; set; }
}
public class UserConfiguration : EntityTypeConfiguration<Users>
{
public UserConfiguration() : base()
{
HasKey(p => p.UserId);
Property(e => e.Username)
.IsUnicode(false)
.IsRequired()
.HasMaxLength(50);
Property(e => e.Password)
.IsUnicode(false)
.IsRequired()
.HasMaxLength(50);
Property(a => a.Active).IsRequired();
Property(d => d.RegDate).IsRequired();
HasOptional(u => u.Token).WithRequired(u => u.User);
}
}
public class TokenConfiguration: EntityTypeConfiguration<Token>
{
public TokenConfiguration()
{
HasKey(p => p.TokenId);
Property(p => p.TokenId).HasMaxLength(50);
Property(p => p.TokenValue).HasColumnName("Token").IsRequired().HasMaxLength(500);
Property(p => p.Active).IsRequired();
Property(p => p.Fecalt).IsRequired();
ToTable("Tokens");
}
}
我有以下例外:
列名“User_UserId”无效。\r\n列名“User_UserId”无效。\r\n列名“User_UserId”无效。”
生成的查询是这样的(显然是错误的):
SELECT [Extent1].[UserId] AS [UserId], [Extent1].[Username] AS [Username], [Extent1].[Password] AS [Password], [Extent1].[Active] AS [Active], [ Extent1].[RegDate] AS [RegDate], [Extent3].[TokenId] AS [TokenId], [Extent3].[UserId] AS [UserId1], [Extent3].[Token] AS [Token], [Extent3] .[Active] AS [Active1], [Extent3].[Fecalt] AS [Fecalt], [Extent3].[User_UserId] AS [User_UserId] FROM [dbo].[Users] AS [Extent1] LEFT OUTER JOIN [dbo] .[Tokens] AS [Extent2] ON [Extent1].[UserId] = [Extent2].[User_UserId] LEFT OUTER JOIN [dbo].[Tokens] AS [Extent3] ON [Extent1].[UserId] = [Extent3] .[User_UserId]
查询如下:
var query = from p in efContext.Users
.Include( p =>p.Token)
select p;
外键分配不当,左连接重复,但我不知道如何修复它。
关系在用户中:
HasOptional(u => u.Token).WithRequired(u => u.User);
注册用户为 1 到 0..1,用户令牌可选,PK/FK 关系为 UserID。