【问题标题】:Entity Framework Code First one-to-one relationEntity Framework Code First 一对一关系
【发布时间】:2011-01-17 16:35:12
【问题描述】:

我正在尝试在两个表之间创建一对一的关系,但结果是我是一对多的。这段代码有什么问题?

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

【问题讨论】:

  • 我在 Content 类中没有看到 KeyAttribute。
  • 密钥由 EFCF 自动检测,它是 - ID。我使用 fluent API 解决了这个问题,但 Steel 在保存内容方面存在一些问题。
  • 如果我没记错的话,当属性命名为Id,或者ClassNameId时,假定为主键

标签: c# ef-code-first poco


【解决方案1】:

Content 类中不需要 PostId,Post 类中不需要 ContentId 吗?

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

这个怎么样:)这应该可以。

【讨论】:

    【解决方案2】:

    问题已通过删除解决

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

    之后我们就不需要使用 Fluent API 但我在保存时遇到了一些问题。

    【讨论】:

      【解决方案3】:
      猜你喜欢
      • 2016-06-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-12
      • 2011-04-07
      • 1970-01-01
      相关资源
      最近更新 更多