I'm using a code from a tutorial to try things out that I'll need in my real project. I have a table in my DataBase with a lot (16) Foreign Keys in it I have to recreate the whole DataBase using ADO.NET EF and now I'm little stuck with this particular case. Here is the code that I'm using for testing purposes:

public class Blog
    {
        public int BlogId { get; set; }
        public string Name { get; set; }
        public string Url { get; set; }

        public int UserId { get; set; }
        public virtual User User { 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 int BlogId1 { get; set; }
        public virtual Blog Blog1 { get; set; }

        //public int BlogId2 { get; set; }
        public virtual Blog Blog2 { get; set; }

        //public int BlogId3 { get; set; }
        public virtual Blog Blog3 { get; set; }

        //public int BlogId4 { get; set; }
        public virtual Blog Blog4 { get; set; }
    }

I've commented the int properties as it seems that I don't need them. Executing this code I get the following:

enter image description here

So there are two thing that concerns me at the moment - is this the way to add multiple Foreign Keys at one table and if so - the two rows underlined with red - why I have Blog_BlogId and Blog_BlogId1 before I get the expected Blog1_.., Blog2_...?

有帮助吗?

解决方案

Ok, I lost the post here from where I got the solution but in this particular case it seems to be some sort of naming convention I have to uncomment the commented code and change the names without using numbers or underscore. Then in OnModelCreating event add this code as many times as I need :

modelBuilder.Entity<Post>().HasRequired(c => c.Blog)
                                  .WithMany(m => m.Posts)
                                  .HasForeignKey(c => c.BlogId)
                                  .WillCascadeOnDelete();

            modelBuilder.Entity<Post>().HasRequired(c => c.Blogged)
                                          .WithMany()
                                          .HasForeignKey(c => c.BloggedId)
                                          .WillCascadeOnDelete(false);

Notice that I change the property name and the class instance name every time I add new record for foreign key.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top