我有很多在我的模型很多關係:多對多關係插入不正確
Tag.cs
public class Tag
{
// more properites ...
// user relations with forgin key
public User CreatedBy { get; set; }
public Guid CreatedById { get; set; }
// has many posts
public ICollection<Post> Posts { get; set; }
}
這裏是標籤Canfiguration:
HasRequired(o => o.CreatedBy)
.WithMany(user => user.Tags)
.HasForeignKey(tag => tag.CreatedById)
.WillCascadeOnDelete(false);
Post.cs
public class Post
{
public ICollocation<Tag> Tag { get; set; }
}
及配置:
HasMany(post => post.Tags)
.WithMany(tag => tag.Posts)
.MapToStoredProcedures();
這裏是我插入後有多個標籤插入操作代碼:
public async Task InsertAsync(CreatePost postDto)
{
using (var transaction = _uow.Database.BeginTransaction())
{
// map dto class to Post
var post = _mapper.Map<Post>(postDto);
// here split tag names in dto
var postTgs = postDto.TagNames.Split(',');
// i get tags that contains postTags names
var tags = await _tags.AsNoTracking().Where(x => postTgs.Contains(x.Name)).ToListAsync().ConfigureAwait(false);
_posts.Add(post);
await _uow.SaveAllChangesAsync().ConfigureAwait(false);
// get added post for add tags
var newPost = await _posts.Include(o => o.Tags).SingleAsync(x => x.Id == post.Id).ConfigureAwait(false);
foreach (var tag in tags)
{
// here add tags
newPost.Tags.Add(new Tag(){Name = tag.Name,CreatedById = tag.CreatedById});
}
await _uow.SaveAllChangesAsync().ConfigureAwait(false);
transaction.Commit();
}
}
問題是,它在數據庫中插入多個標籤插入柱標籤。這opration添加新標籤標籤表但我想添加存在標籤PostTags Ef生成它Automaticaly。
- 我該如何解決這個問題?
- 爲什麼此操作插入新標籤?
我解決這個問題看其他文件和問題,但沒有得到result.I認爲我必須在我的模型來解決這一創造PostTags。
注:標記與用戶有外鍵。