EF4 Code First: как добавить отношения без добавления свойства навигации
Как мне определить отношения, используя Code First, но без каких-либо свойств навигации?
Ранее я определил одно-много и много-много, используя свойства навигации в обоих концах отношения. И соответствующие отношения создаются в базе данных. здесь урезанная версия того, как выглядят классы (для простоты я преобразовал отношения Many-Many в one-many).
public class User
{
public string UserId { get; set; }
public string PasswordHash { get; set; }
public bool IsDisabled { get; set; }
public DateTime AccessExpiryDate { get; set; }
public bool MustChangePassword { get; set; }
public virtual Role Role { get; set; }
}
public class Role
{
public int RoleId { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public virtual ICollection<User> Users { get; set; }
public virtual ICollection<Right> Rights { get; set; }
}
public class Right
{
public Guid RightId { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public virtual Role Role { get; set; }
}
Однако, если я удаляю свойства навигации, отношения не создаются. Вот как выглядят классы.
public class User
{
public string UserId { get; set; }
public string PasswordHash { get; set; }
public bool IsDisabled { get; set; }
public DateTime AccessExpiryDate { get; set; }
public bool MustChangePassword { get; set; }
public int Role RoleId { get; set; }
}
public class Role
{
public int RoleId { get; set; }
public string Name { get; set; }
public string Description { get; set; }
}
public class Right
{
public Guid RightId { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public int RoleId { get; set; }
}
обратите внимание, что вместо свойства навигации у меня есть первичный ключ связанной таблицы. Все создается на столе - кроме отношений. Итак, как мне это сделать?
Кстати, я пробовал различные комбинации в методе OnModelCreating для dbcontext, но безрезультатно. Любая помощь очень ценится!
Спасибо,
Мел
Ответы
Ответ 1
Я считаю, что вам всегда нужно свойство навигации, по крайней мере, на одной стороне при первом использовании кода. Затем вы сможете его сопоставить:
public class User
{
public string UserId { get; set; }
public string PasswordHash { get; set; }
public bool IsDisabled { get; set; }
public DateTime AccessExpiryDate { get; set; }
public bool MustChangePassword { get; set; }
public int RoleId { get; set; }
public Role Role { get; set; }
}
public class Role
{
public int RoleId { get; set; }
public string Name { get; set; }
public string Description { get; set; }
}
public class Right
{
public Guid RightId { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public int RoleId { get; set; }
public Role Role { get; set; }
}
public class TestContext : DbContext
{
public TestContext() : base("Entities")
{}
protected override void OnModelCreating(System.Data.Entity.ModelConfiguration.ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<User>()
.HasRequired(r => r.Role)
.WithMany()
.HasForeignKey(r => r.RoleId);
modelBuilder.Entity<Right>()
.HasRequired(r => r.Role)
.WithMany()
.HasForeignKey(r => r.RoleId);
}
}
Ответ 2
Вы можете использовать свободно api, чтобы добавить отношения, хотя код конфигурации отличается от кода сущности, что делает его менее доступным.
Ответ 3
В EF 4.3 вы можете добавить миграцию, которая добавляет отношения.