简体   繁体   English

实体框架代码第一个一对一关系

[英]Entity Framework Code First one-to-one relation

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? 您在Content类中不需要PostId,在Post类中不需要ContentId吗?

        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. 之后,我们不需要使用Fluent API,但是我在保存时遇到了一些问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM