如何在Entity Framework 4.1的Code-First Fluent API中以编程方式定义关系 [英] How to define relationships programmatically in Entity Framework 4.1's Code-First Fluent API

查看:92
本文介绍了如何在Entity Framework 4.1的Code-First Fluent API中以编程方式定义关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在玩新的EF4.1独角兽爱情。



我正在尝试了解可以使用代码优先的不同方法程式化定义了几个简单的POCO之间的关系。



如何定义以下=>


  1. 1 团队有0多个用户秒。 (和用户在1 团队

  2. 1 用户有0-or-1 Foo (但$ Foo 没有财产回到用户

  3. 1 用户有1 UserStuff


解决方案

您正在寻找的示例:

  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. 1 Team has 0-many Users. (and a User is in 1 Team)
  2. 1 User has 0-or-1 Foo's (but a Foo has no property going back to a User)
  3. 1 User has 1 UserStuff

解决方案

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屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆