c# – 如何在Entity Framework 4.1的Code-First Fluent API中以编程方式定义关系

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

我想了解不同的方式,我可以使用代码优先来编程定义我的几个简单的POCO之间的关系.

如何定义以下=>

> 1团队拥有0多个用户. (和一个用户在1团队)
> 1用户具有0或-1 Foo(但是Foo没有返回给用户的属性)
> 1用户拥有1个UserStuff

在这里你有你正在寻找的例子:

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();
    }
}
http://stackoverflow.com/questions/5368029/how-to-define-relationships-programmatically-in-entity-framework-4-1s-code-firs

本站文章除注明转载外,均为本站原创或编译
转载请明显位置注明出处:c# – 如何在Entity Framework 4.1的Code-First Fluent API中以编程方式定义关系