更新时间:2023-02-13 14:39:18
问题是在 Admin $ c $中的两个
名称
c>和 Staff
当然不能同时映射到中的
。名称
属性
但是您可以有两个不同的名称属性,并将两者映射到两个表中的相同列名称:
用户
中的更改:
public用户
{
[Key]
public string Username {get;组; }
...
public string AdminName {get;组; }
public string StaffName {get;组; }
...
}
映射片段:
.Map(map =>
{
map.Properties(p => new
{
p.Username,
p.AdminName
});
map.Property(p => p.AdminName).HasColumnName(Name);
map.ToTable(Admin);
})。Map(map =>
{
map.Properties(p => new
{
p.Username,
p.StaffName,
p.Phone,
p.Position
});
map.Property(p => p.StaffName) .HasColumnName(Name);
map.ToTable(Staff);
});
I'm facing a problem using EF. I have the following situation:
Table User: Username, Password, RoleId, IsActive, CreatedDate, ActivedDate
Table Admin: Username, Name
Table Staff: Username, Name, Position, Phone
From this database schema i'd like to generate the following entity by merge tables data:
public class User
{
[Key]
public string Username { get; set; }
public string Password { get; set; }
public int RoleId { get; set; }
public bool IsActive { get; set; }
public DateTime CreatedDate { get; set; }
public DateTime ActivedDate { get; set; }
public string Name { get; set; }
public string Phone { get; set; }
public string Position { get; set; }
[ForeignKey("RoleId")]
public Role Role { get; set; }
}
configuration class:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<User>()
.Map(map =>
{
map.Properties(p => new
{
p.Username,
p.Password,
p.RoleId,
p.IsActive,
p.CreatedDate,
p.ActivedDate
});
map.ToTable("User");
})
.Map(map =>
{
map.Properties(p => new
{
p.Username,
p.Name
});
map.ToTable("Admin");
}).Map(map =>
{
map.Properties(p => new
{
p.Username,
p.Name,
p.Phone,
p.Position
});
map.ToTable("Staff");
});
base.OnModelCreating(modelBuilder);
}
I've tested it but it doesn't work as expected. I always get this message:
Properties for type 'User' can only be mapped once. The non-key property 'Name' is mapped more than once. Ensure the Properties method specifies each non-key property only once.
Am I missing something?
The problem is that the two Name
s in Admin
and Staff
of course can't both be mapped onto one Name
property in User
.
But you can have two different name properties and map both to the same column names in two tables:
Changes in User
:
public class User
{
[Key]
public string Username { get; set; }
...
public string AdminName { get; set; }
public string StaffName { get; set; }
...
}
And the mapping fragments:
.Map(map =>
{
map.Properties(p => new
{
p.Username,
p.AdminName
});
map.Property(p => p.AdminName).HasColumnName("Name");
map.ToTable("Admin");
}).Map(map =>
{
map.Properties(p => new
{
p.Username,
p.StaffName,
p.Phone,
p.Position
});
map.Property(p => p.StaffName).HasColumnName("Name");
map.ToTable("Staff");
});