问题
I have two entities, User and Feedback, and there is one-to-many relationship between those with help of the username field.
Feedback --> User
-------- --------
username username
However, sometimes feedback may code from an unregistered user, and Username field on Feedback will be Null. In that case, the addition of feedback will fail due to the foreign key constraint.
How can I disable the enforcement of a foreign key constraint on a relationship declaratively or by means of the Fluent API? It is enabled by default when the DB is created.
Thank you!
回答1:
You don't need to disable the enforcement of the foreign key constraint for your purpose, you just need to allow NULL values for the foreign key which is called an optional one-to-many relationship (in contrast to a required relationship which doesn't allow NULL values of the foreign key).
You can define this optional relationship the following way:
public class Feedback
{
public int Id { get; set; }
[ForeignKey("User")]
public int? UserId { get; set; }
public User User { get; set; }
}
Having a nullable type int?
for the foreign key makes the relationship optional. If User
has a primary key property named Id
you can even omit the [ForeignKey]
attribute because Entity Framework will detect UserId
as the foreign key of the User
navigation property based on naming conventions.
Alternatively instead of data annotations you can use Fluent API:
modelBuilder.Entity<Feedback>()
.HasOptional(f => f.User)
.WithMany() // or WithMany(u => u.Feedbacks)
.HasForeignKey(f => f.UserId);
来源:https://stackoverflow.com/questions/10324231/how-to-prevent-code-first-from-enabling-foreign-key-constraint-on-a-relationship