私のソリューションには次のマップがあります
public BlogMap() {
Table("Blogs");
LazyLoad();
Id(x => x.BlogId).GeneratedBy.Identity().Column("BlogId");
Map(x => x.BlogName).Column("BlogName").Not.Nullable();
Map(x => x.BlogCreateDate).Column("BlogCreateDate");
Map(x => x.PostCount).Column("PostCount");
HasMany(x => x.BlogPosts).KeyColumn("BlogId");
}
public BlogPostMap() {
Table("BlogPosts");
LazyLoad();
CompositeId().KeyProperty(x => x.PostId, "PostId").KeyProperty(x => x.BlogId,`enter code here` "BlogId");
References(x => x.Blog).Column("BlogId");
Map(x => x.PostText).Column("PostText");
Map(x => x.CreateDate).Column("CreateDate");
}
1 つのブログに多数のブログ投稿が含まれる場合があります
新しい BlogPost を作成してデータベースに保存しようとしています。以下は私がそれをやろうとしている方法ですが、うまくいきません。
BlogPost newbgPost = new BlogPost();
newbgPost.BlogId = currMasterBlogId;
newbgPost.CreateDate = DateTime.Now;
newbgPost.PostText = newPostText;
newbgPost.PostId = newPostId+1;
repBlogPost.Save(newbgPost);
上記のコードReferences(x => x.Blog).Column("BlogId");
は、BlogPost マップで削除すると機能します。
新しい BlogPost が Blog で参照を探していることは理解しています。newbgPost.BlogId = currMasterBlogId;
これは基本的に、BlogPost に参照させたい BlogId を使用して行うことができます。
以下はBlogPostクラスです
public class BlogPost {
public virtual int PostId { get; set; }
public virtual int BlogId { get; set; }
public virtual Blog Blog { get; set; }
public virtual string PostText { get; set; }
public virtual System.Nullable<System.DateTime> CreateDate { get; set; }
#region NHibernate Composite Key Requirements
public override bool Equals(object obj) {
if (obj == null) return false;
var t = obj as BlogPost;
if (t == null) return false;
if (PostId == t.PostId && BlogId == t.BlogId)
return true;
return false;
}
public override int GetHashCode() {
int hash = 13;
hash += PostId.GetHashCode();
hash += BlogId.GetHashCode();
return hash;
}
#endregion
}
ブログクラス:
public class Blog {
public Blog() {
BlogPosts = new List<BlogPost>();
}
public virtual int BlogId { get; set; }
public virtual string BlogName { get; set; }
public virtual System.Nullable<System.DateTime> BlogCreateDate { get; set; }
public virtual System.Nullable<int> PostCount { get; set; }
public virtual IList<BlogPost> BlogPosts { get; set; }
}