How to prevent Code First from enabling foreign key constraint on a relationship?

耗尽温柔 提交于 2019-12-11 08:37:31

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!