如何在Entity Framework 4.1的Code-First Fluent API中以编程方式定义关系 [英] How to define relationships programmatically in Entity Framework 4.1's Code-First Fluent API
本文介绍了如何在Entity Framework 4.1的Code-First Fluent API中以编程方式定义关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试了解可以使用代码优先的不同方法以程式化定义了几个简单的POCO之间的关系。
如何定义以下=>
- 1
团队
有0多个用户
秒。 (和用户
在1团队
) - 1
用户
有0-or-1Foo
(但$Foo
没有财产回到用户
) - 1
用户
有1UserStuff
解决方案
您正在寻找的示例:
public class User
{
public int Id {get;组; }
...
public Foo Foo {get;组; }
public Team Team {get;组; }
public UserStuff UserStuff {get;组; }
}
public class Team
{
public int Id {get;组; }
...
public ICollection< User>用户{get;组; }
}
public class Foo
{
public int Id {get;组; }
...
}
public class UserStuff
{
public int Id {get;组; }
...
}
public class上下文:DbContext
{
public DbSet< User>用户{get;组; }
public DbSet&Foo> Fo子组; }
public DbSet< Team>团队{get;组; }
public DbSet< UserStuff> UserStuff {get;组;
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity< User>()
.HasRequired(u => u.Team)
.WithMany(t => t.Users);
modelBuilder.Entity< User>()
.HasOptional(u => u.Foo)
.WithRequired();
modelBuilder.Entity< User>()
.HasRequired(u => u.UserStuff)
.WithRequiredPrincipal();
}
}
I'm playing around with the new EF4.1 unicorn love.
I'm trying to understand the different ways I can use code-first to programatically define my relationships between a few simple POCO's.
How can I define the following =>
- 1
Team
has 0-manyUser
s. (and aUser
is in 1Team
) - 1
User
has 0-or-1Foo
's (but aFoo
has no property going back to aUser
) - 1
User
has 1UserStuff
解决方案
Here you have examples you are looking for:
public class User
{
public int Id { get; set; }
...
public Foo Foo { get; set; }
public Team Team { get; set; }
public UserStuff UserStuff { get; set; }
}
public class Team
{
public int Id { get; set; }
...
public ICollection<User> Users { get; set; }
}
public class Foo
{
public int Id { get; set; }
...
}
public class UserStuff
{
public int Id { get; set; }
...
}
public class Context : DbContext
{
public DbSet<User> Users { get; set; }
public DbSet<Foo> Foos { get; set; }
public DbSet<Team> Teams { get; set; }
public DbSet<UserStuff> UserStuff { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<User>()
.HasRequired(u => u.Team)
.WithMany(t => t.Users);
modelBuilder.Entity<User>()
.HasOptional(u => u.Foo)
.WithRequired();
modelBuilder.Entity<User>()
.HasRequired(u => u.UserStuff)
.WithRequiredPrincipal();
}
}
这篇关于如何在Entity Framework 4.1的Code-First Fluent API中以编程方式定义关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文