簡體   English   中英

實體框架未以1:0..1關系插入相關記錄(意外結果)

[英]Entity Framework not inserting a related record in a 1:0..1 relationship (Unexpected result)

自從我上一篇文章以來已經有一段時間了,這一次我需要一些幫助,以了解使用Code-First方法在c#中使用Entity Framework(SQL Server)進行的操作。

讓我告訴你我的代碼:

Blog.cs

using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;

namespace Helper.Models
{
    public class Blog
    {
        [Key]
        public int BlogId { get; set; }
        public string BlogTitle { get; set; }
        public virtual ICollection<Post> Posts { get; set; }
        public virtual Author Author { get; set; }
    }
}

Author.cs

using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace Helper.Models
{
    public class Author
    {
        [Key,ForeignKey("Blog")]
        public int AuthorId { get; set; }
        public string Name { get; set; }
        public string Address { get; set; }
        public virtual Blog Blog { get; set; }
    }
}

RegularAuthor.cs

using System;

namespace Helper.Models
{
    public class RegularAuthor : Author
    {
        public DateTime DateOfFirstBlogPost { get; set; }
    }
}

GuestAuthor.cs

namespace Helper.Models
{
    public class GuestAuthor : Author
    {
        public string OriginalBlogAccess { get; set; }
    }
}

DefaultDB.cs

using Helper.Models;
using System.Data.Entity;

    namespace EF_Basics
    {
        public class DefaultDB : DbContext
        {
            public DefaultDB(): base("EFDemo")
            {

            }
            public DbSet<Blog> Blogs { get; set; }
            public DbSet<Post> Posts { get; set; }
            public DbSet<Category> Categories { get; set; }
            public DbSet<Author> Authors { get; set; }
        }
    }

Program.cs中

using Helper.Models;
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace EF_Basics
{
    class Testing
    {
        static void Main(string[] args)
        {
            TestInsert2();
            Console.WriteLine("Press any key to exit...");
            Console.ReadLine();
        }

        private static void TestInsert2()
        {
            using (DefaultDB ctx = new DefaultDB())
            {
                RegularAuthor author1 = new RegularAuthor()
                {
                    Name = "First Author",
                    Address = GetLocalIpAddress(),
                    DateOfFirstBlogPost = DateTime.Now
                };

                GuestAuthor guest1 = new GuestAuthor()
                {
                    Name = "Second Author",
                    Address = GetLocalIpAddress(),
                    OriginalBlogAccess = "Never"
                };

                List<Blog> BlogList = new List<Blog>()
                {
                    new Blog
                    {
                        Author = author1,
                        BlogTitle = "Mid Century Modern DIY Dog House Build"
                    },
                    new Blog
                    {
                        Author = guest1,
                        BlogTitle = "Elf Doughnut Box Printable"
                    },
                    new Blog
                    {
                        Author = author1,
                        BlogTitle = "5 Ways to Make Giant Candy for a Candyland Theme"
                    }
                };

                foreach (var blog in BlogList)
                {
                    Console.WriteLine($"Adding '{blog.BlogTitle}' by '{blog.Author.Name}'");
                    ctx.Blogs.Add(blog);
                    Thread.Sleep(1000);
                    Console.WriteLine();
                }

                ctx.SaveChanges();
            }
        }

        private static string GetLocalIpAddress()
        {
            var host = Dns.GetHostEntry(Dns.GetHostName());
            foreach (var ip in host.AddressList)
            {
                if (ip.AddressFamily == AddressFamily.InterNetwork)
                {
                    return ip.ToString();
                }
            }
            throw new Exception("No network adapters with an IPv4 address in the system!");
        }
    }
}

所以...現在我們有了所有相關的代碼,當我運行它們時,所有這些信息都將“大部分”信息存入數據庫,但是最后一條記錄只是忽略了所有作者數據。 運行代碼后,我還提供了SQL快照和結果。

SQL快照和數據庫中的結果數據

我認為問題在於您要將博客添加到數據庫中。 相反,您應該添加作者及其博客列表。

author類應該具有博客列表,因此,當您添加Author實體時,可以根據需要添加任意數量的Blog。

public List<Blog> Blogs { get; set; }

在Blog類中,您可以更改以下內容:

public Author Author { get; set; }

這是應該做什么的一個示例:

    private static void TestInsert2()
    {
     using (DefaultDB ctx = new DefaultDB())
     {
       RegularAuthor author1 = new RegularAuthor()
       {
         Name = "First Author",
         Address = GetLocalIpAddress(),
         DateOfFirstBlogPost = DateTime.Now
       };
       GuestAuthor guest1 = new GuestAuthor()
       {
        Name = "Second Author",
        Address = GetLocalIpAddress(),
        OriginalBlogAccess = "Never"
       };

    author1.Blogs = new List<Blog>
    {
       new Blog        
       {
         Author = author1,
         BlogTitle = "Mid Century Modern DIY Dog House Build"
       },
        new Blog
       {
         Author = author1,
         BlogTitle = "5 Ways to Make Giant Candy for a Candyland Theme"
       }
    }

    guest1.Blogs = new List<Blog>
    {
       new Blog
       {
         Author = guest1,
         BlogTitle = "Elf Doughnut Box Printable"
       }
    }
    context.Add(author1);
    context.Add(guest1);
    ctx.SaveChanges();
    }
   }

由於博客由author對象中的Blog屬性引用,因此它們將被添加到數據庫中

編輯:

這已經付出了一些努力,但是我想我有解決方案。 表關系不正確。

您想要做的是讓一個擁有很多博客的作者。 現在這意味着作者對象必須具有博客集合。

您必須具有的關系如下:

在此處輸入圖片說明

在這種情況下,博客具有作者的外鍵,並且如我的主要回答所建議,作者類必須具有博客的集合:

public partial class Author
{  
    public Author()
    {
        Blogs = new HashSet<Blog>();
    }
    public int authorId { get; set; }
    public string name { get; set; }
    public virtual ICollection<Blog> Blogs { get; set; }
}

同時Blog類:

public partial class Blog
{
    public int blogId { get; set; }
    public string blogTitle { get; set; }
    public int? authorId { get; set; }
    public virtual Author Author { get; set; }
}

您的模型將是:

   public Model1()
    {
    }

    public virtual DbSet<Author> Authors { get; set; }
    public virtual DbSet<Blog> Blogs { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Author>()
            .Property(e => e.name)
            .IsUnicode(false);

        modelBuilder.Entity<Blog>()
            .Property(e => e.blogTitle)
            .IsUnicode(false);
    }

在運行代碼之前:

在此處輸入圖片說明

運行代碼后:

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM