【问题标题】:specifying the foreign key to the table programmatically by using fluentapi使用 fluentapi 以编程方式指定表的外键
【发布时间】:2011-08-19 13:58:21
【问题描述】:

嗨,有没有可能使用实体为表分配外键......

请参阅此问题以进行澄清。how do add a single entry for two tables using linq to entities

让我解释清楚.....

      i have a product table    product_id
                                product_name 
                                product_description
                                category_id


                                category table
                                category_id
                                category_name 

不幸的是,在创建表时不可能将 category_id 指定为外键,它自己将 category_id 作为列而不是外键的实体表

所以..我想将此指定为外键所以..是否可以通过编程方式指定为外键 任何人都可以有使用fluent api指定外键的示例代码

【问题讨论】:

  • 嗯?以编程方式是什么意思??? sql,前端asp.net php???
  • 我正在使用 c# 和 mysql 以及实体关系...
  • @laurence 喜欢在实体中指定导航属性...

标签: c# linq entity-framework linq-to-entities


【解决方案1】:

如果您使用的是 EntityFramework 4.1,则可以使用 Fluent API,它允许您指定键名和其他关联属性。

【讨论】:

    【解决方案2】:

    这是我在 EF 4.1 CodeFirst 中如何做到这一点的示例。我认为,您可以使用非常相似的方法。

    public class P
    {
        public string Id { get; set; }
        public string Name { get; set; }
        public string Desc { get; set; }
        public string CategoryId { get; set; }
    }
    
    public class C
    {
        public string Id { get; set; }
        public string Name { get; set; }
    }
    
    public class ProductsContext : DbContext
    {
        public DbSet<P> Products { get; set; }
        public DbSet<C> Categories { get; set; }
    
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Entity<P>().HasRequired(p => p.CategoryId).WithRequiredDependent();
        }
    }
    

    在 OnModelCreating 中,您告诉上下文,要如何设置关系,即使 DB 中没有这样的关系。

    【讨论】:

      猜你喜欢
      • 2020-05-29
      • 2010-10-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多