我想在没有外键的两个表中插入行。
在 startup.cs 文件中
public void ConfigureServices(IServiceCollection services)
{
services.AddHealthChecks();
services.AddDbContext<wUtilityContentContext>(opts => opts.UseSqlServer(
Algorithm.Decrypt(Configuration["ConnectionStrings:wUtilityContent_ConnectionString"]),
b => b.MigrationsAssembly(typeof(Startup).GetTypeInfo().Assembly.GetName().Name)));
services.AddUnitOfWorkPool(optionsBuilder =>
{
optionsBuilder.AddUnitOfWork<wUtilityContentContext>("Content");
});
services.AddScoped<IContentUow, ContentUow>();
services.AddScoped<AuditCoreLog>();
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
....
}
在 ContentService.cs 文件中
public class ContentServices : ContentServiceBase
{
private readonly AuditCoreLog _auditLog;
private readonly IContentUow _contentUow;
public ContentServices(IContentUow contentUow, AuditCoreLog auditLog)
{
_contentUow = contentUow;
_auditLog = auditLog;
}
public override Task<MessageResponse> CategoryInsertUpdate(CategoryInsertUpdate_Request request, ServerCallContext context)
{
var response = new MessageResponse() { };
try
{
int _RESPONSE_EXISTED_CATE = -2;
int _RESPONSE_NOT_EXISTS_CATE = -3;
int _nHotOrder = 0;
var findnHotOrder = _contentUow.Category.Where(p => p.ParentId == request.ParentId).ToList();
if (findnHotOrder != null && findnHotOrder.Count > 0)
_nHotOrder = findnHotOrder.Max(x => x.OrderNo).GetValueOrDefault();
var insertCategory = _contentUow.Category.Add(new TblCategory()
{
ParentId = request.ParentId,
Alias = request.Alias,
OrderNo = _nHotOrder + 1,
Status = request.Status,
CreatedDate = DateTime.Now,
CreatedUser = request.CreatedUser,
SystemId = request.SystemId,
ImageUrl = request.ImageUrl
});
_contentUow.SaveChanges(); //savechange to DB -> get id identity
var _categoryId = insertCategory.Entity.Id;
var insertCategoryContent_vi = _contentUow.CategoryContent.Add(new TblCategoryContent()
{
CategoryId = _categoryId,
CategoryName = request.CategoryNameVi,
CategoryContent = request.CategoryContentVi,
LanguageId = (int)PaymentApps_PaymentLanguage.VN
});
var insertCategoryContent_en = _contentUow.CategoryContent.Add(new TblCategoryContent()
{
CategoryId = _categoryId,
CategoryName = request.CategoryNameEn,
CategoryContent = request.CategoryContentEn,
LanguageId = (int)PaymentApps_PaymentLanguage.EN
});
_contentUow.SaveChanges();
_contentUow.CommitTransaction();
response.ResponseStatus = ErrorCodes.SUCCESS;
}
catch (Exception ex)
{
response.ResponseStatus = ErrorCodes.SYSTEM_ERROR;
_contentUow.RollbackTransaction();
}
}
}