我正在定义两个如下所示的实体,但正在发生一种奇怪的行为:
[Table("ClientTypes", Schema="dbo")]
public ClientType {
[Key]
public int Id { get; set; }
public string Name { get; set; }
}
[Table("Clients", Schema="dbo")]
public Client {
[Key]
public long Id { get; set; }
[ForeignKey("ClientTypeId")]
public int ClientTypeId { get; set; }
public virtual ClientType ClientType { get; set; }
}
我正在为ClientTypeId
属性填充一些值,但ClientType
对象没有任何内容。有人可以帮我这个吗?
谢谢大家!
答案 0 :(得分:2)
您拥有的ForeignKey
属性位于错误的属性上。
可以将注释放在外键属性上并指定关联的导航属性名称,或者将其放在导航属性上并指定关联的外键名称。
- source
[ForeignKey("ClientTypeId")]
应该装饰public virtual ClientType ClientType
,
或将其更改为[ForeignKey("ClientType")]
并将其保留在原位。
答案 1 :(得分:0)
您是否急切地加载了该值?
var clients = context.Clients.Include("ClientType").ToList();
答案 2 :(得分:0)
选择客户端时,您必须Include
客户端类型
Client cli = (from c in db Clients.Include("ClientType")//or the name of the property
select c).First();
这转换为左连接并选择Client和ClientType的数据。
如果跳过Include
,EF将在执行语句时仅为客户端选择数据。
正如迈克所说,如果上下文仍然可用,那么当你访问它时,属性将被延迟加载。