ADO.NET EF如何使用Code First设置FK

时间:2013-02-14 09:17:28

标签: constraints code-first ado.net-entity-data-model

我有这些描述我的数据库模型的类:

 public class Blog
    {
        public int BlogId { get; set; }
        public string Name { get; set; }
        public string Url { get; set; }

        public virtual List<Post> Posts { get; set; }
    }

    public class Post
    {
        public int PostId { get; set; }
        public string Title { get; set; }
        public string Content { get; set; }

        public int BlogId { get; set; }
        public virtual Blog Blog { get; set; }
    }

    public class User
    {
        public int UserId { get; set; }
        public string Username { get; set; }
        public string DisplayName { get; set; }
    }

    public class BloggingContext : DbContext
    {
        public DbSet<Blog> Blogs { get; set; }
        public DbSet<Post> Posts { get; set; }
        public DbSet<User> Users { get; set; }
    }

它工作正常,但是当我尝试在App.Config中添加FK约束时,这样:

  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework">
      <parameters>
        <parameter value="System.Data.SqlClient" />
      </parameters>
    </defaultConnectionFactory>
    <Association Name="UserBlogs">
      <End Type="CodeFirstNewDatabaseSample.BloggingContext.User" Role="User" Multiplicity="1" >
        <OnDelete Action="Cascade" />
      </End>
      <End Type="CodeFirstNewDatabaseSample.BloggingContext.Blog" Role="Blog" Multiplicity="*" />
      <ReferentialConstraint>
        <Principal Role="User">
          <PropertyRef Name="UserId" />
        </Principal>
        <Dependent Role="Blog">
          <PropertyRef Name="UserId" />
        </Dependent>
      </ReferentialConstraint>
    </Association>
  </entityFramework>

我收到App.Config has threw an error的错误。如何使用此代码作为示例添加FKeys并且App.Config是正确的位置?

1 个答案:

答案 0 :(得分:1)

模型构建器是我使用实体框架配置FK的首选方法

查看我的博文,其中详细介绍了如何执行此操作:http://blog.staticvoid.co.nz/2012/7/17/entity_framework-navigation_property_basics_with_code_first