我正在使用CodeFirst CTP5。使用CodeFirst刪除一對多關係的問題CTP5
正如你在我的代碼中看到的,我有一個用戶有很多問題。我希望能夠刪除用戶但保留問題。另外,我也想保持問題
public class User
{
public User()
{
Questions = new List<Question>();
}
public virtual string UserId { get; set; }
public virtual ICollection<Question> Questions { get; set; }
}
public class Question
{
public virtual string QuestionId { get; set; }
public virtual string Title { get; set; }
public virtual string Text { get; set; }
public User User { get; set; }
public string UserId { get; set; }
}
public class DB : DbContext
{
public DbSet<User> Users { get; set; }
public DbSet<Question> Questions { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<User>()
.HasMany(u => u.Questions)
.WithRequired(q => q.User)
.HasForeignKey(q => q.UserId)
.WillCascadeOnDelete(false);
}
}
問題的「用戶ID」的性質是這樣的配置的ModelCreating給了我這個錯誤:
System.Data.Edm.EdmAssociationType: : Multiplicity is not valid in Role 'Expert_Answers_Source' in relationship 'Expert_Answers'. Because all the properties in the Dependent Role are nullable, multiplicity of the Principal Role must be '0..1'
我在做什麼錯?我怎麼才能得到它?
Hi @Ladislav。如果我沒有使用流利的API配置它,外鍵仍然會被創建。有沒有一種方法(使用流暢的api)來避免創建外鍵,同時保留我的屬性名稱(UserId ...)? – Subgurim 2011-03-12 09:50:50
我認爲這是由於默認配置的約定:'NavigationPropertyNameForeignKeyDiscoveryConvention' – 2011-03-12 10:08:00