Blog Model
using System.Collections.Generic;
namespace DataLayer
{
public class Blog
{
public int BlogKey { get; set; }
public string Title { get; set; }
public string BloggerName { get; set; }
public virtual Post Post { get; set; }
}
}
Post Model
using System;
using System.Collections.Generic;
namespace DataLayer
{
public class Post
{
public int PostKey { get; set; }
public string Title { get; set; }
public DateTime? DateCreated { get; set; }
public string Content { get; set; }
public virtual Blog Blog { get; set; }
}
}
Model Configurations
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.ModelConfiguration;
namespace DataLayer
{
public class BlogConfiguration : EntityTypeConfiguration<Blog>
{
public BlogConfiguration()
{
ToTable("Blog", "dbo");
HasKey(k => k.BlogKey).Property(p=>p.BlogKey).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
// This will allow having null Post for the Blog
//HasRequired(p => p.Post).WithRequiredPrincipal(p => p.Blog).WillCascadeOnDelete(false);
// This will NOT allow having no Post for the Blog
HasRequired(p => p.Post).WithRequiredPrincipal(p => p.Blog).Map(m=>m.MapKey("OtherBlogKeyColumn")).WillCascadeOnDelete(false);
}
}
public class PostConfiguration : EntityTypeConfiguration<Post>
{
public PostConfiguration()
{
ToTable("Post", "dbo");
HasKey(k => k.PostKey).Property(p=>p.PostKey).HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
}
}
}
Client
using DataLayer;
using System;
namespace Client
{
class Program
{
static void Main(string[] args)
{
MyDbContext c = new MyDbContext();
//Works when dependent's foreign key column is mapped to the primary key column(this is by default when Map() is not provided).
//Doesn't work when foreign key column is mapped to some other column(which is provided by Map())
Blog blog = new Blog { Title = "world", Post = null, BloggerName = "suyash" };
//Blog required, Post required
//Blog blog = new Blog { Title = "work", Post = new Post { Title = "new world post" }, BloggerName = "suyash" };
c.Blogs.Add(blog);
c.SaveChanges();
}
}
}
I have the models Blog
and Post
. The relationship to discuss here is HasRequired().WithRequired(). I want Blog to be Principal and Post to be Dependent. Please see the Blog Configuration.
HasRequired(p => p.Post).WithRequiredPrincipal(p => p.Blog).WillCascadeOnDelete(false);
allows a null Post with Blog blog = new Blog { Title = "world", Post = null, BloggerName = "suyash" };
But, HasRequired(p => p.Post).WithRequiredPrincipal(p => p.Blog).Map(m=>m.MapKey("OtherBlogKeyColumn")).WillCascadeOnDelete(false);
doesn't.
The configuration with Map() works as expected, it throws an error when we try to insert a null Post.
Isn't the whole purpose of HasRequired().WithRequired() is to ensure that both the ends have a value even if Map() was not used. Currently without Map() it works just like HasOptional(Blog).WithRequired(Post).
I want to understand is this a genuine error or am i missing something here.