specifying the foreign key to the table programmatically by using fluentapi

半城伤御伤魂 提交于 2019-12-14 04:22:29

问题


hi is there any possibility to assign a foriegnkey to table using entity ....

pls see this question for clarification.. how do add a single entry for two tables using linq to entities

let me explain clearly.....

      i have a product table    product_id
                                product_name 
                                product_description
                                category_id


                                category table
                                category_id
                                category_name 

unfortunately it is not posssible to specify the category_id as a foreign key at the time of creating table the entity table it self taken the category_id as a column not as a foreign key

so.. i want to specify this one as foreign key so.. is it possible to specify as a foreign key by programmatically can any one have sample code for specifying foreignkey using fluent api


回答1:


If you're using EntityFramework 4.1, you can use the Fluent API, which allows you to specify key names and other association properties.




回答2:


Here`s a sample, of how I did that in EF 4.1 CodeFirst. I think, you can use very similar aproach.

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();
    }
}

In the OnModelCreating, you tell context, how want to set relations, even if there are no such relations in DB.



来源:https://stackoverflow.com/questions/7122677/specifying-the-foreign-key-to-the-table-programmatically-by-using-fluentapi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!