EF4 CTP5 - 映射没有对象引用的外键?

Posted

技术标签:

【中文标题】EF4 CTP5 - 映射没有对象引用的外键?【英文标题】:EF4 CTP5 - Map foreign key without object references? 【发布时间】:2011-03-05 22:42:35 【问题描述】:

我觉得这应该有一个简单的答案,但我找不到。

我有 2 个 POCO:

public class Category

    public int Id  get; set; 
    public string Name  get; set; 


public class Product

    public int Id  get; set; 
    public int CategoryId  get; set; 

请注意,两个 POCO 上都没有对象引用。使用 Code-First,如何让 EF4 CTP5 定义两个数据库表之间的关系?

(我知道这是一个不寻常的场景,但我正在探索 Code-First 的可能性和不可能性)

【问题讨论】:

【参考方案1】:

不,这是不可能的。正如您在下面看到的,所有用于设置关联的 fluent API 方法都需要指定 Navigation Property 作为其参数。

HasMany<TTargetEntity>(Expression<Func<TEntityType, ICollection<TTargetEntity>>> navigationPropertyExpression) 

HasOptional<TTargetEntity>(Expression<Func<TEntityType, TTargetEntity>> navigationPropertyExpression) 

HasRequired<TTargetEntity>(Expression<Func<TEntityType, TTargetEntity>> navigationPropertyExpression) 

【讨论】:

谢谢。我也是这么想的。 实际上,如果我不使用 Code-First 并且我破解了 csdl/msl/ssdl 文件,您认为这可能吗? 我不这么认为,但我不确定,不过你可以试一试。【参考方案2】:

您是否有什么特别的原因不想使用对象引用?使用它们看起来非常优雅:

public class Category

    public int Id  get; set; 
    public string Name  get; set; 
    public virtual ICollection<Product> Products  get; set; 


public class Product

    public int Id  get; set; 
    public Category Category  get; set; 

您仍然可以通过您的产品以product.Category.Id 访问类别 ID。

【讨论】:

如前所述,我正在探索 Code-First 的可能性和不可能性。

以上是关于EF4 CTP5 - 映射没有对象引用的外键?的主要内容,如果未能解决你的问题,请参考以下文章