我有以下课程:
public class Client {
public virtual Guid ClientID { get; set; }
public virtual string ClientName { get; set; }
public virtual IList<ClientMonthlyRevenue> Revenue { get; set; }
...
public virtual void SetMonthlyRevenue(int year, int month, double revenue)
{
// Make sure it's not null... this might happen depending on how the client is created
if (Revenue == null)
Revenue = new List<ClientMonthlyRevenue>();
// Check for existance - we don't want any duplicates
ClientMonthlyRevenue clientMonthlyRevenue = Revenue.Where(x => x.Year == year && x.Month == month).FirstOrDefault();
if (clientMonthlyRevenue == null)
{
// If it doesn't exist, create a new one and add to the list
clientMonthlyRevenue = new ClientMonthlyRevenue(this, year, month, revenue);
this.Revenue.Add(clientMonthlyRevenue); // This is the line throwing the error
}
else
{
// If it exists, just update it
clientMonthlyRevenue.Revenue = revenue;
}
}
}
public class ClientMonthlyRevenue {
public virtual Client ParentClient { get; set; }
public virtual int Year { get; set; }
public virtual int Month { get; set; }
public virtual double Revenue { get; set; }
...
}
这两个映射:
public class ClientMap : ClassMap<Client>
{
Id(x => x.ClientID).GeneratedBy.Assigned();
Map(x => x.ClientName);
HasMany<ClientMonthlyRevenue>(x => x.Revenue)
.Table("ClientMonthlyRevenue")
.KeyColumn("ClientID")
.Cascade.All()
.Fetch.Join();
}
public class ClientMonthlyRevenueMap : ClassMap<ClientMonthlyRevenue>
{
CompositeId()
.KeyReference(x => x.Client, "ClientID")
.KeyProperty(x => x.Year)
.KeyProperty(x => x.Month);
Map(x => x.Revenue);
}
当我从数据库中获取客户端时:
Client client = Session.Get<Client>(clientID);
所有数据都在那里,这很棒。但是当我尝试添加一个新的ClientMonthlyRevenue子项时:
client.Revenue.Add(new ClientMonthlyRevenue(this.ClientID, year, month, revenue));
我收到错误:
Collection was of a fixed size.
我在这里遗漏或误解了什么吗?我需要修改什么才能将项目添加到此持久列表?
答案 0 :(得分:1)
我会将Client对象更改为具有以下内容:
public class Client
{
public Client()
{
Revenue = new List<ClientMonthlyRevenue>();
}
public virtual Guid ClientID { get; set; }
public virtual string ClientName { get; set; }
public virtual IList<ClientMonthlyRevenue> Revenue { get; set; }
public virtual void AddRevenue(ClientMonthlyRevenue revenue)
{
revenue.ParentClient = this;
Revenue.Add(revenue);
}
}
然后你可以这样打电话:
public void TestMapping()
{
session.BeginTransaction();
var client = new Client{ClientID = Guid.NewGuid()};
session.SaveOrUpdate(client);
client = session.Get<Client>(client.ClientID);
client.AddRevenue(new ClientMonthlyRevenue(2001,07,1200));
session.Transaction.Commit();
}
您收到的错误听起来可能会在堆栈中创建得更高。我能够重新创建你的场景。查看完整来源:https://gist.github.com/1098337
答案 1 :(得分:0)
您是否尝试将收藏品标记为Inverse?我不知道它是否有帮助。
HasMany<ClientMonthlyRevenue>(x => x.Revenue)
.Table("ClientMonthlyRevenue")
.KeyColumn("ClientID")
.Cascade.All()
.Fetch.Join()
.Inverse();