开发者

Entity Framework Code First one-to-one relation

开发者 https://www.devze.com 2023-02-05 16:17 出处:网络
I\'m trying to create a one-to-one relation between two tables, but as a result I have one-to-many. What is the problem with开发者_如何学编程 this code?

I'm trying to create a one-to-one relation between two tables, but as a result I have one-to-many. What is the problem with开发者_如何学编程 this code?

namespace EFCF_Demo.Models
{
    public class Post
    {
        [Key]
        public int ID { get; set; }
        public string Title { get; set; }
        public string MiniContent { get; set; }
        public string Author { get; set; }
        public DateTime PublishDate { get; set; }
        public int Rating { get; set; }
        public virtual Content MainContent { get; set; }   
    }

    public class Content
    {
        public int ID { get; set; }
        public virtual Post Post { get; set; }
        public string FullContent { get; set; }
    }

    public class PostEntities : DbContext
    {
        public DbSet<Post> Posts { get; set; }
        public DbSet<Content> Contents { get; set; }
    }
}


Don't you need PostId in the Content class, and ContentId in the Post class?

        public class Content
        {
            [Key]
            public int PostId { get; set; }
            public virtual Post Post { get; set; }
            public string FullContent { get; set; }
        }

what about this:) This should do it.


Problem was resolved by removing

public DbSet<Content> Contents { get; set; }

After that we don't need to use the Fluent API but I have some problems with saving.


Try this:

  • http://social.msdn.microsoft.com/Forums/eu/adonetefx/thread/4b5a46e0-f5c2-4c38-a73c-0038eaef2537
  • How to declare one to one relationship using Entity Framework 4 Code First (POCO)
0

精彩评论

暂无评论...
验证码 换一张
取 消