我是Entity Framework的新手,我希望能帮助他们在一个" join table"中插入数据。
我有三个表,Profiles
,Tags
和一个名为ProfilesTags
的表连接这两个表。类是从database / DB First自动生成的。
public partial class Profiles
{
public Profiles()
{
this.ProfilesTags = new HashSet<ProfilesTags>();
}
public int ProfileId { get; set; }
public string Name { get; set; }
...
public virtual ICollection<ProfilesTags> ProfilesTags { get; set; }
}
public partial class Tags
{
public Tags()
{
this.ProfilesTags = new HashSet<ProfilesTags>();
}
public int TagId { get; set; }
public string Tag { get; set; }
public virtual ICollection<ProfilesTags> ProfilesTags { get; set; }
}
public partial class ProfilesTags
{
public int Id { get; set; }
public int ProfileId { get; set; }
public int TagId { get; set; }
public virtual Tags Tags { get; set; }
public virtual Profiles Profiles { get; set; }
}
我有SaveTags
方法,如下所示:
public void SaveTags(int profileId, IEnumerable<TagsNameValue> tags)
{
var pr = Context.Profiles.First(p => p.ProfileId == profileId);
// remove any existing
pr.ProfilesTags.Clear();
if (tags == null || !tags.Any())
return;
var ids = tags.Select(value => value.Value);
var names = tags.Select(value => value.Name);
// get a list of tags for lookup from [Tags]-table
var tagsList = Context.Tags.Where(t => ids.Any(v => t.TagId == v) || names.Any(v => t.Tag == v)).ToList();
foreach (var nameValue in tags)
{
var tag = tagsList.FirstOrDefault(t => t.TagId == nameValue.Value || t.Tag.ToLower() == nameValue.Name.ToLower());
// Tag is already in [Tags], no need to recreate id, just associate it.
if (tag != null)
{
var tagModel = new ProfilesTags()
{
TagId = nameValue.Value,
ProfileId = profileId
};
pr.ProfilesTags.Add(tagModel);
}
// create new item in [Tags] table first and add association [ProfilesTags]
else
{
var newTag = new Tags { Tag = nameValue.Name};
// how do I associate this newly added tag to pr.ProfilesTags ?
// what to do / how to procede?
Context.Tags.Add(newTag);
}
}
Context.SaveChanges()
}
如何将newTag
与pr.ProfilesTags
相关联?
答案 0 :(得分:1)
似乎newTag
应首先拥有有效的ID,然后再按ProfilesTags
建立关系。
// create new item in [Tags] table first and add association [ProfilesTags]
else
{
var newTag = new Tags { Tag = nameValue.Name};
// how do I associate this newly added tag to pr.ProfilesTags ?
// what to do / how to procede?
Context.Tags.Add(newTag);
// Let newTag has a valid tagId
Context.SaveChanges();
// Build the relationship between `Profiles` and `Tags`.
var newProfileTag = new ProfilesTags();
/// Build the relationship by ForeignKey,
/// Or, call pr.ProfilesTags.Add(newProfileTag)
newProfileTag.ProfiledId = pr.ProfileId;
newProfileTag.TagId = newTag.TagId; //< It SHOULD NOT be zero...
Context.ProfilesTags.Add(newProfileTag);
// Save the newProfileTag.....
// Context.SaveChanges();
}