Reputation: 177
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?
Upvotes: 1
Views: 444
Reputation: 16174
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 User
property to null
on 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.
Upvotes: 1
Reputation: 364279
It is not possible. Once you defined foreign key you can't delete user and still use his Id in question. If you delete user his Id will be set to null in Question
. It is not about EF but about referential integrity in database. If you don't want this to happen you can't define UserId
in Question
as foreign key. If you do not define it as db foreign key you will not have relation mapped in your entities.
Upvotes: 1