Question

I have these classes that describes my DB 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; }
    }

It's working fine, but when I try to add FK constraint in App.Config like this:

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

I get an error that App.Config has threw an error. How can I add FKeys using this code as a sample and is App.Config the right place to do that?

Was it helpful?

Solution

The modelbuilder is my preferred method of configuring FKs with Entity Framework

Check out my blog post which goes into the details of how to do this here: http://blog.staticvoid.co.nz/2012/7/17/entity_framework-navigation_property_basics_with_code_first

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top