I’m working with CodeFirst CTP5.
As you can see in my code I have a User with many Questions. I want to be able to delete the User but keeping the Question. In addition, I also want to keep the “UserId” property of the Question
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);
}
}
The problem is that configuring the ModelCreating like this gives me this error:
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’
What am I doing wrong? How can I get it?
As Ladislav says, it is not possible, but you could try and work around it by adding an extra User Id property to the Question class (with corresponding column to your Questions table) and name it something like RefUserId or OriginalPoster, or whatever you like. You’d fill this property manually and not use it as foreign key.
Then, before deleting the user just set the
Userproperty tonullon the Question object and delete the user. That should leave the Question intact in the database and you’d still have a reference to the user who posted the question.