问题描述
我有两个实体,用户和反馈,并且在用户名字段的帮助之间有一对多的关系。 反馈 - >用户
-------- --------
用户名用户名
但是,有时反馈可能会从未注册的用户进行编码,反馈上的用户名字段将为空。在这种情况下,由于外键约束,添加反馈将失败。
如何以声明方式或通过Fluent API禁用对关系对外键约束的强制执行?创建数据库时,默认情况下启用。
谢谢!
您不需要禁用为了您的目的执行外键约束,您只需要为外键允许NULL值,这个外键称为可选一对多关系(与必需关系,不允许外键的NULL值)。
您可以通过以下方式定义此可选关系:
public class Feedback
{
public int Id {get;组; }
[ForeignKey(User)]
public int? UserId {get;组; }
public User User {get;组;
}
具有可空类型 int?
为外键使关系可选。如果用户
具有名为 Id
的主键属性,您甚至可以省略 [ForeignKey] / code>属性,因为Entity Framework将检测
UserId
作为用户
导航属性的外键命名约定
或者,您可以使用Fluent API替代数据注释:
modelBuilder.Entity< Feedback>()
.HasOptional(f => f.User)
.WithMany()//或WithMany(u => u.Feedbacks)
.HasForeignKey(f => f.UserId);
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!
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);
这篇关于如何防止代码首先启用外键约束关系?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!