问题
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