[英]FluentNhibernate Mapping Dictionaries Foreign Key Remains Null
I have a simple Fluent-NHibernate mapping that gives me a headache! 我有一个简单的Fluent-NHibernate映射让我头疼! I'm trying to map a dictionary for one of the entities, but its FK remains null. 我正在尝试为其中一个实体映射字典,但其FK仍然为空。
Here's the entities code: 这是实体代码:
public class Person
{
public Person()
{
PhoneNumbers = new Dictionary<string, Phone>();
}
public virtual int Id { get; set; }
public virtual string Name { get; set; }
public virtual IDictionary<string, Phone> PhoneNumbers { get; set; }
}
public class Phone
{
public virtual int Id { get; set; }
public virtual string Type { get; set; }
public virtual string Number { get; set; }
}
Now, Here's the mapping: 现在,这是映射:
public class PersonClassMap : ClassMap<Person>
{
public PersonClassMap()
{
Id(x => x.Id).GeneratedBy.Identity();
Map(x => x.Name);
HasMany(x => x.PhoneNumbers).AsMap(y => y.Type).Cascade.All();
}
}
public class PhoneClassMap : ClassMap<Phone>
{
public PhoneClassMap()
{
Id(x => x.Id).GeneratedBy.Identity();
Map(x => x.Type);
Map(x => x.Number);
}
}
Last, Here's the Test I'm doing: 最后,这是我正在做的测试:
static void Main(string[] args)
{
ConfigureSessionFactory();
using (var session = _sessionFactory.OpenSession())
{
var john = new Person();
john.Name = "John";
Phone home = new Phone
{
Type = "Home",
Number = "12345"
};
john.PhoneNumbers.Add(home.Type, home);
session.Save(john);
}
}
For some reason, when I look in the database, the phone record's Person_id
remains null, and when I load the person back from the DB, the PhoneNumbers
dictionary remains empty. 出于某种原因,当我查看数据库时,电话记录的Person_id
保持为空,当我从数据库加载该人时, PhoneNumbers
字典保持为空。
Why? 为什么? And how to solve this issue? 以及如何解决这个问题? What am I mapping wrong? 我映射错了什么?
This issue was finally resolved by adding Transactions. 最终通过添加事务解决了此问题。 I have no idea why that works (which makes me quite sad, actually), but it does. 我不知道为什么会这样(这实际上让我很伤心),但确实如此。
using (var session = _sessionFactory.OpenSession())
{
var transaction = session.BeginTransaction();
john.Name = "John";
Phone home = new Phone
{
Type = "Home",
Number = "12345"
};
john.PhoneNumbers.Add(home.Type, home);
session.Save(john);
transaction.Commit();
}
Hope that helps you too, as it took me 3 hours too long to get this right. 希望对你有所帮助,因为我花了3个小时太长时间才能做到这一点。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.