I have two related classes like these :
public partial class WorkItem
{
public WorkItem()
{
this.ChildWorkItems = new HashSet<WorkItem>();
this.Attachments = new HashSet<Attachment>();
}
public int Id { get; set; }
public Nullable<int> ParentId { get; set; }
public string Title { get; set; }
public string SenderUserName { get; set; }
public virtual ICollection<WorkItem> ChildWorkItems { get; set; }
public virtual WorkItem ParentWorkItem { get; set; }
public virtual ICollection<Attachment> Attachments { get; set; }
}
and the realted 1-n attachments :
public partial class Attachment
{
public int Id { get; set; }
public string Filename { get; set; }
public Nullable<int> WorkItemId { get; set; }
public virtual WorkItem WorkItem { get; set; }
}
Now I want to insert some new workitems
with their attachment into the database. I use the following code for insertion :
at first put all workitems (regardless of their attachments )
var workItems = new List<WorkItem>();
foreach (var username in AllUsers)
{
var workitem = new WorkItem();
//fill the simple fields
lst.Add(workitem);
Context.WorkItems.Add(workitem);
}
then set the attachments :
foreach (var fileName in MYFILES)
{
var file = new System.IO.FileInfo(fileName);
foreach (var workItem in workItems)
{
var att =
new Attachment()
{
Filename = file.Name,
};
context.Attachments.Add(att);
att.WorkItem = workItem;
}
}
But I get the following exception :
Multiplicity constraint violated. The role 'WorkItem' of the relationship 'AienCRMModel.FK_WorkItemAttachments_WorkItems' has multiplicity 1 or 0..1.
The interesting point is if I only have One workitem
, everything is ok. If I have more than one WorkItem
with no attachments , again everything is ok. The problem raises when having more than one WorkItem with at least one attachment.
I read lots of other post but nothing usefuk was found.
NOTE : I use EF Code-First 4.3 with a T4 template which generate my classes from the EDMX file.
I Really appreciate your helps in advance.
EDIT
I Attached the full EDMX diagram of mentioned tables here :
EDIT 2
Complete .edmx file at here : http://www.4shared.com/file/zQUO_qk7/CrmModel141.html?