问题描述
考虑两个类。
public class File
{
[Key]
public string Id {get;组; }
public string Message_Id {get;组; }
内部消息消息{get;组;
}
public class Message
{
[Key]
public string Id {get;组; }
}
在EF6中,对于N:1..0关系,这个流利API。
modelBuilder.Entity< File>()
.HasOptional(e => e.Message)。 WithMany()。HasForeignKey(e => e.Message_Id);
Entiity Framework Core 1中的等价物是什么?
谢谢
在EF 7中找不到等效的方法。按照惯例,CLR类型可以包含 null
将被配置为可选。那么,如果FK属性是可空的, a>或不分别。
总之,由于您的 Message_Id
FK属性为字符串
,它已经接受 null
值,因此如果您使用以下Fluent Api配置:
$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ b $ e => e.Message_Id)
EF将配置您的关系为可选。
如果您的FK属性是值类型,如 int
,则应声明为空( int?
)。
另外我注意到现在你有一个导航属性,具有内部
访问修饰符。您应该始终将您的实体属性声明为 public
。
Consider two classes.
public class File
{
[Key]
public string Id { get; set; }
public string Message_Id { get; set; }
internal Message Message { get; set; }
}
public class Message
{
[Key]
public string Id { get; set; }
}
In EF6, for N : 1..0 relation there was this fluent API.
modelBuilder.Entity<File>()
.HasOptional(e => e.Message ).WithMany().HasForeignKey(e => e.Message_Id);
What is equivalent in Entiity Framework Core 1?
Thank you
You will not find an equivalent method in EF 7. By convention, a property whose CLR type can contain null
will be configured as optional. So what decide if the relationship is optional or not is if the FK property is nullable or not respectively.
In summary, due to your Message_Id
FK property is string
, it already accepts null
value, so if you use the following Fluent Api configuration:
modelBuilder.Entity<File>()
.HasOne(s => s.Message)
.WithMany()
.HasForeignKey(e => e.Message_Id)
EF will configure your relationship as optional.
In case of your FK property is value type like int
, you should declare it as nullable (int?
).
Also I noticed now you have a navigation property with internal
access modifier. You should always declare your entity properties as public
.
这篇关于相当于实体框架核心1(EF7)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!