我正在尝试使用linq2sql将它们插入两个关联的表中,但是我的代码仅插入一个实体(电子邮件),但没有任何异常-仅未插入另一个实体(附件)。
我认为我在关联中的某个地方有一个错误,但是我不知道如何正确设置它。
感谢帮助。
插入代码:
using (TransactionScope main_transaction = new TransactionScope(TransactionScopeOption.Required, TimeSpan.FromSeconds(120)))
{
foreach (var attachment in attachmets)
email.Attachments.Add(attachment);
_emails.InsertOnSubmit(email);
_context.SubmitChanges();
main_transaction.Complete();
}
Pocos:
[Table(Name = "maily")]
internal class Email
{
private EntitySet<Attachment> _attachments;
public Email()
{
this._attachments = new EntitySet<Attachment>();
}
[Column(IsPrimaryKey = true, IsDbGenerated = true, Name = "ID_mailu", AutoSync = AutoSync.OnInsert)]
public virtual int ID_mailu { get; set; }
[Association(Storage = "_attachments", OtherKey = "id_mailu")]
public ICollection<Attachment> Attachments
{
get { return _attachments.ToList(); }
set { _attachments.Assign(value); }
}
}
[Table(Name = "MailPrilohy")]
internal class Attachment
{
private EntityRef<Email> _email;
public Attachment()
{
_email = default(EntityRef<Email>);
}
[Column(IsPrimaryKey =true, IsDbGenerated = true, Name = "id_prilohy", CanBeNull = false, AutoSync = AutoSync.OnInsert)]
public int Id_Prilohy { get; set; }
[Column(Name = "id_mailu", CanBeNull = false, IsDbGenerated = true)]
public int id_mailu { get; set; }
[Association(Storage = "_email", ThisKey = "id_mailu", OtherKey = "ID_mailu", IsForeignKey = true)]
public Email Email
{
get { return _email.Entity; }
set { _email.Entity = value; }
}
}
}
答案 0 :(得分:0)
为了通过LINQ插入到两个相关的表中,如果您的表之间具有主键/外键关系,那么您还有两个可以相互链接的对象。一个非常基本的例子:
MyDataContext _dbcontext = new MyDataContext();
ItemType t = new ItemType();
t.type= "Snacks";
MenuItem m = new MenuItem();
m.type= "Party Snacks";
t.ItemType.Add(m);
_dbcontext.ItemTypes.Add(t);
_dbcontext.SubmitChanges();
上面的示例在将更改提交到ItemTypes
实体时将添加您的对象和所有链接的对象。另外请注意,要使此功能正常工作,两个表中都必须有一个主键。否则LINQ无法为您提供链接的可能性。
答案 1 :(得分:0)
所以我刚刚解决了这个问题...
问题出在几个地方。
1s是关联错过的外键属性..
[Association(Storage = "_email", ThisKey = "id_mailu", OtherKey = "ID_mailu", IsForeignKey = true)]
public Email Email
{
get { return _email.Entity; }
set { _email.Entity = value;}
}
接下来,我应该插入附件->而不是电子邮件。
_context.Attachments.InsertAllOnSubmit(attachmets);
答案 2 :(得分:-1)
您能尝试看看是否适合您吗?
using (TransactionScope main_transaction = new TransactionScope(TransactionScopeOption.Required, TimeSpan.FromSeconds(120)))
{
foreach (var attachment in attachmets)
attachment.Email = email; // only this line changed
_emails.InsertOnSubmit(email);
_context.SubmitChanges();
main_transaction.Complete();
}