After Adding a Include property on the parent model controller I am facing the following error:
'Microsoft.EntityFrameworkCore.Query.InvalidIncludePathError': Unable to find navigation ' CurrencyList' specified in string based include path ' CurrencyList'. This exception can be suppressed or logged by passing event ID 'CoreEventId.InvalidIncludePathError' to the 'ConfigureWarnings' method in 'DbContext.OnConfiguring' or 'AddDbContext'.'
I am sharing all the related class & model.
CurrencyList (Model) : This is the child class which I want to include into the parent class for populating the dropdown.
public class CurrencyList
{
[Key]
public int Id { get; set; }
[DisplayName("CURRENCY")]
[Required(ErrorMessage = "CURRENCY is a required field")]
public string? CurrencyName { get; set; }
[DisplayName("EXCHANGE RATE")]
[Required(ErrorMessage = "EXCHANGE RATE is a required field")]
public double Rate { get; set; }
}
CurrencyList Controller:
public class CurrencyListController : ControllerBase
{
private readonly IUnitOfWork _unitOfWork;
public CurrencyListController(IUnitOfWork unitOfWork)
{
_unitOfWork = unitOfWork;
}
[HttpGet]
public IEnumerable<CurrencyList> Get()
{
IEnumerable<CurrencyList> objCurrencyDropDownList = _unitOfWork.Currency.GetAll();
return _unitOfWork.Currency.GetAll();
}
[HttpGet("{id:int}")]
public CurrencyList GetDetails(int id)
{
return _unitOfWork.Currency.GetDetails(id);
}
[HttpPost]
[ProducesResponseType(StatusCodes.Status201Created)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
public IActionResult Create(CurrencyList obj)
{
if (ModelState.IsValid)
{
_unitOfWork.Currency.Add(obj);
_unitOfWork.Save();
return CreatedAtAction("GetDetails", new { id = obj.Id }, obj);
}
return BadRequest();
}
[HttpPut]
[ProducesResponseType(StatusCodes.Status204NoContent)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
public IActionResult Edit(CurrencyList obj)
{
if (ModelState.IsValid)
{
_unitOfWork.Currency.Update(obj);
_unitOfWork.Save();
return NoContent();
}
return BadRequest();
}
[HttpDelete]
[ProducesResponseType(StatusCodes.Status204NoContent)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public IActionResult Delete(int? id)
{
var obj = _unitOfWork.Currency.GetFirstOrDefault(c => c.Id == id);
if (obj == null)
{
return NotFound();
}
_unitOfWork.Currency.Remove(obj);
_unitOfWork.Save();
return NoContent();
}
}
BTBNewLienOpening (Model) : This is the parent class where I created FK retalion with CurrencyList Model.
public class BTBNewLienOpening
{
[Key]
public int ExpLCNoId { get; set; }
[DisplayName("EXPORT L/C NO")]
[ValidateNever]
public string? ExpLCNo { get; set; }
[DisplayName("ORDER NO")]
[ValidateNever]
public string? OrderNo { get; set; }
[DisplayName("STYLE")]
public int? StyleListId { get; set; }
[ForeignKey("StyleListId")]
[ValidateNever]
public StyleList? StyleList { get; set; }
[DisplayName("VALUE")]
[ValidateNever]
[DisplayFormat(DataFormatString = "{0:C}", ApplyFormatInEditMode = false)]
public decimal? Value { get; set; }
[DisplayName("NET VALUE")]
[ValidateNever]
[DisplayFormat(DataFormatString = "{0:C}", ApplyFormatInEditMode = false)]
public decimal? NetValue { get; set; }
[DisplayName("CURRENCY")]
public int? CurrencyListId { get; set; }
[ForeignKey("CurrencyListId")]
[ValidateNever]
public CurrencyList? CurrencyList { get; set; }
[DisplayName("QTY PCS")]
[ValidateNever]
public string? QtyPcs { get; set; }
[DisplayName("SHIPMENT")]
[ValidateNever]
public string? Shipment { get; set; }
[DisplayName("EXPIRY DATE")]
[ValidateNever]
public string? Expiry { get; set; }
[DisplayName("COUNTRY")]
public int? CountryListId { get; set; }
[ForeignKey("CountryListId")]
[ValidateNever]
public CountryList? CountryList { get; set; }
}
BTBNewLienOpeningController : This is the controller where I use the include properties for including all the dropdown properties. In the GetAll() method I use the include properties and include the dropdown properties. If I run the program without CurrencyList the app works fine. But after adding CurrencyList it shows the Microsoft.EntityFrameworkCore.Query.InvalidIncludePathError'
public class BTBNewLienOpeningController : ControllerBase
{
private readonly IUnitOfWork _unitOfWork;
private readonly ILogger<BTBNewLienOpeningController> _logger;
public BTBNewLienOpeningController(IUnitOfWork unitOfWork, ILogger<BTBNewLienOpeningController> logger)
{
_unitOfWork = unitOfWork;
_logger = logger;
}
[HttpGet]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status500InternalServerError)]
public IActionResult GetNewLienOpening()
{
try
{
IEnumerable<BTBNewLienOpening> objBTBNewLienOpeningList = _unitOfWork.BTBNewLienOpening.GetAll(includeProperties: "StyleList, CurrencyList, CountryList");
return Ok(objBTBNewLienOpeningList);
}
catch (Exception ex)
{
_logger.LogError(ex, $"Something went wrong in the {nameof(GetNewLienOpening)}");
return StatusCode(500, "Internal Server Error, Please Try Again Leter!");
}
}
[HttpGet("{id:int}")]
public BTBNewLienOpening GetDetails(int id)
{
return _unitOfWork.BTBNewLienOpening.GetDetails(id);
}
//[Authorize(Roles = "Administrator")]
[HttpPost]
[ProducesResponseType(StatusCodes.Status201Created)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[ProducesResponseType(StatusCodes.Status500InternalServerError)]
public IActionResult Create(BTBNewLienOpening obj)
{
if (ModelState.IsValid)
{
_unitOfWork.BTBNewLienOpening.Add(obj);
_unitOfWork.Save();
return CreatedAtAction("GetDetails", new { id = obj.ExpLCNoId }, obj);
}
_logger.LogError($"Something went wrong in the {nameof(Create)}");
return StatusCode(500, "Internal Server Error, Please Try Again Leter!");
}
[HttpPut]
[ProducesResponseType(StatusCodes.Status202Accepted)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[ProducesResponseType(StatusCodes.Status500InternalServerError)]
public IActionResult Update(BTBNewLienOpening obj)
{
if (ModelState.IsValid)
{
_unitOfWork.BTBNewLienOpening.Update(obj);
_unitOfWork.Save();
return StatusCode(202, "Successfully Updated!");
}
_logger.LogError($"Something went wrong in the {nameof(Update)}");
return StatusCode(500, "Internal Server Error, Please Try Again Leter!");
}
[HttpDelete]
[ProducesResponseType(StatusCodes.Status204NoContent)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[ProducesResponseType(StatusCodes.Status500InternalServerError)]
public IActionResult Delete(int? id)
{
if (id < 1)
{
_logger.LogError($"Invalid Delete Attempt In {nameof(Delete)}");
return BadRequest();
}
try
{
var obj = _unitOfWork.BTBNewLienOpening.GetFirstOrDefault(c => c.ExpLCNoId == id);
if (obj == null)
{
_logger.LogError($"Invalid Delete Attempt In {nameof(Delete)}");
return BadRequest("Submitted Data Is Invalid");
}
_unitOfWork.BTBNewLienOpening.Remove(obj);
_unitOfWork.Save();
return NoContent();
}
catch (Exception ex)
{
_logger.LogError(ex, $"Something Went Wrong In The {nameof(Delete)}");
return StatusCode(500, "Internal Server Error, Please Try Again Leter!");
}
}
}
Repository (Class) : Here I use the GetAll method and added the include functionality.
public class Repository<T> : IRepository<T> where T : class
{
private readonly ApplicationDbContext _db;
internal DbSet<T> dbSet;
public Repository(ApplicationDbContext db)
{
_db = db;
this.dbSet = _db.Set<T>();
}
public void Add(T entity)
{
dbSet.Add(entity);
}
public IEnumerable<T> GetAll(string? includeProperties = null)
{
IQueryable<T> query = dbSet;
if (includeProperties != null)
{
foreach (var includeProp in includeProperties.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
{
query = query.Include(includeProp);
}
}
return query.ToList();
}
public T GetFirstOrDefault(Expression<Func<T, bool>> filter, string? includeProperties = null)
{
IQueryable<T> query = dbSet;
query = query.Where(filter);
if (includeProperties != null)
{
foreach (var includeProp in includeProperties.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
{
query = query.Include(includeProp);
}
}
return query.FirstOrDefault();
}
public T GetDetails(int id)
{
return dbSet.Find(id);
}
public void Remove(T entity)
{
dbSet.Remove(entity);
}
public void RemoveRange(IEnumerable<T> entity)
{
dbSet.RemoveRange(entity);
}
public IEnumerable<T> GetProp(string? includeProperties = null)
{
IQueryable<T> query = dbSet;
if (includeProperties != null)
{
foreach (var includeProp in includeProperties.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
{
query = query.Include(includeProp);
}
}
return query.ToList();
}
}
Related
I'm using blazor (blazorise datagrid) with asp.net core and entity framework. I'm facing a problem while trying to perform crud operation on data with
foreign key column (complex object).
Here is my code
Model Classes
public partial class ApproverSequence
{
public int Id { get; set; }
public int? TransactionTypeId { get; set; }
public bool? IsStart { get; set; }
public bool? IsArchived { get; set; }
public virtual TransactionType TransactionType { get; set; }
}
public partial class TransactionType
{
public TransactionType()
{
ApproverSequences = new HashSet<ApproverSequence>();
}
public int Id { get; set; }
public string Description { get; set; }
public bool? IsArchived { get; set; }
public virtual ICollection<ApproverSequence> ApproverSequences { get; set; }
}
Here is my data grid column
<DataGridSelectColumn TItem="ApproverSequence" Field="#nameof(ApproverSequence.TransactionType)" Caption="Description" Editable="true">
<DisplayTemplate>
#{
var transactionTypeDesc = (context as ApproverSequence).TransactionType?.Description;
#transactionTypeDesc
}
</DisplayTemplate>
<EditTemplate>
<Select TValue="int"
SelectedValue="#((int)((TransactionType)(((CellEditContext)context).CellValue)).Id)"
SelectedValueChanged="#( v => ((CellEditContext)context).CellValue = transactionTypes.First(x=> x.Id == v))">
#foreach (var item in transactionTypes)
{
<SelectItem TValue="int" Value="#(item.Id)">#item.Description</SelectItem>
}
</Select>
</EditTemplate>
</DataGridSelectColumn>
#code{
private List<ApproverSequence> approverSequences;
private List<TransactionType> transactionTypes;
protected override async Task OnInitializedAsync()
{
approverSequences = await ApproverSequenceService.GetAll();
transactionTypes = await TransactionTypeService.GetAll();
}
}
Services
public async Task<List<ApproverSequence>> GetAll()
{
try
{
return await _context.ApproverSequences.Include(x=>x.TransactionType).Where(x => x.IsArchived == false).ToListAsync();
}
catch
{
throw;
}
}
public async Task<List<TransactionType>> GetAll()
{
try
{
return await _context.TransactionTypes.Where(x => x.IsArchived == false).ToListAsync();
}
catch
{
throw;
}
}
while running this project it throws System.NullReferenceException: 'Object reference not set to an instance of an object.' exception.
Is there anything I have missed? Thanks in advance
How to create the dropdown list in one to many relation. I want to populate the category data in Post form and then want to save using POST mode.
Here is my full code:
public class Category
{
public Category()
{
Posts = new Collection<Post>();
}
public int Id{get;set;}
public string Title { get; set; }
}
public class Post
{
public int Id
public string Title { get; set; }
public string Body { get; set; }
public Category Category { get; set; }
public int CategoryId { get; set; }
}
PostFormVM:
public class PostFormVM
{
public int Id { get; set; }
[Required]
public string Title { get; set; }
public string Body { get; set; }
[Required]
public int CategoryId { get; set; }
public IEnumerable<Category> Categories { get; set; }
}
Mapping is here:
public class ApplicationProfile : AutoMapper.Profile
{
public ApplicationProfile()
{
CreateMap<Category, CategoryFormVM>().ReverseMap();
CreateMap<Post, PostFormVM>().ReverseMap();
}
}
Generic Repository implementation
public class GenericRepository<T>:IGenericRepository<T> where T:class
{
private readonly ApplicationDbContext _context;
public GenericRepository(ApplicationDbContextcontext)
{
_context = context;
}
public async Task<List<T>> GetAllAsync()
{
return await _context.Set<T>().ToListAsync();
}
}
ICategoryRepository:
public interface ICategoryRepository:IGenericRepository<Category>
{
}
CategoryRepository implementation
public class CategoryRepository :GenericRepository<Category>, ICategoryRepository
{
public CategoryRepository(ApplicationDbContext context):base(context)
{
}
}
PostRepo Implementation:
public class PostRepository : GenericRepository<Post>, IPostRepository
{
public PostRepository(ApplicationDbContext context) : base(context)
{
}
}
PostController:
public class PostItemController : Controller
{
private readonly IPostRepository _postRepository;
private readonly ICategoryRepository _categoryRepository;
private readonly UserManager<ApplicationUser> _userManager;
private readonly IMapper _mapper;
public PostItemController(IPostRepository postRepository, ICategoryRepository categoryRepository, IMapper mapper, UserManager<ApplicationUser> userManager)
{
_postRepository = postRepository;
_categoryRepository = categoryRepository;
_userManager = userManager;
_mapper = mapper;
}
public IActionResult Create()
{
//Here I want to populate the category data I have used the ViewBag and ViewData here
//I am unable to get the data from the database
ViewBag.Categories= _categoryRepository.GetAllAsync();
return View(new PostFormVM());
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(PostFormVM viewModel)
{
try
{
if (!ModelState.IsValid)
return View("Create", viewModel);
if (ModelState.IsValid) {
//Here I also want to map the selected category item and save to Post table.
var post = _mapper.Map<Post>(viewModel);
post.ApplicationUserId = _userManager.GetUserId(HttpContext.User);
if (viewModel.IsEdit.Equals("false"))
{
await _postRepository.CreateAsync(post);
}
else
{
await _postRepository.UpdateAsync(post);
}
}
}
catch (Exception)
{
}
return RedirectToAction(nameof(Index));
}
I want help to populate the category data in Post Entity Create form.
You can put a breakpoint on this line ViewBag.Categories = _categoryRepository.GetAllAsync();, you can see such a result prompt Result =" {Not yet computed} ", because the method in your generic repository uses the await keyword to operate Asynchronous method, it will wait for the end of the previous process before calculating the result.
Try change you code in Generic Repository like below:
public List<T> GetAllAsync()
{
return _context.Set<T>().ToList();
}
IGenericRepository
public interface IGenericRepository<T> where T : class
{
List<T> GetAllAsync();
}
Show the Category list ,controller
public IActionResult Create()
{
IEnumerable<Category> categories = _categoryRepository.GetAllAsync();
ViewBag.Categories = categories;
return View(new PostFormVM());
}
View
<select asp-for="CategoryId" asp-items="#(new SelectList(ViewBag.Categories,"Id","Title"))"></select>
Result:
Getting the mentioned error when trying to do a GetAll on accounts. It works fine if I go directly to the dbcontext, but gives me the error if I try to work with the repo. I have about 20 others that use just the generic repo and are working great. Because I have additional actions for Accounts, I have created its own repository that implements the generic. I also have several others that work like this and have no problem. The problem is specific to the accounts.
Database of course does have the EmailAddress column, since I can return it if I use dbcontext from the controller instead of the repo.
Any help would be much appreciated.
AccountsController:
public class AccountsController : ControllerBase
{
private readonly AccountRepository _repo;
public AccountsController(DatabaseContext context)
{
_repo = new AccountRepository(context);
}
[HttpGet]
public async Task<ActionResult<IEnumerable<Account>>> GetAccount()
{
// return _context.Account.ToListAsync(); works fine if _context is defined
var accounts = await _repo.GetAll();
if (accounts == null)
return NoContent();
return Ok(accounts); // Gives invalid column error
}
[HttpGet("getaccount")]
public async Task<ActionResult<Account>> GetCurrentAccount()
{
var account = await _repo.GetCurrentAccount(HttpContext.User.Identity.Name);
if (account == null)
{
return NotFound();
}
return account; // Works fine
}
}
Account:
public partial class Account
{
public string Name { get; set; }
public string RefId { get; set; }
public string Position { get; set; }
public bool IsActive { get; set; }
public string EmailAddress { get; set; }
[Key]
public string UserId { get; set; }
}
IAccountRepository:
public interface IAccountRepository : IRepository<Account>
{
Task<Account> GetCurrentAccount(string emailAddress);
}
AccountRepository:
public class AccountRepository : Repository<Account>, IAccountRepository
{
private DatabaseContext _context;
public AccountRepository(DatabaseContext context)
{
_context = context;
}
public async Task<Account> GetCurrentAccount(string emailAddress)
{
var account = await _context.Account
.Where(a => a.EmailAddress == emailAddress)
.FirstOrDefaultAsync();
return account; // this works just fine, and returns with EmailAddress
}
}
IRepository (generic):
public interface IRepository<T>
{
Task<IEnumerable<T>> GetAll();
Task<T> GetById(object id);
void Add(T entity);
void Update(T entity);
void Delete(T entity);
Task<bool> Save();
}
Repository (generic):
public class Repository<T> : IRepository<T> where T : class
{
private DatabaseContext _context;
public Repository()
{
_context = new DatabaseContext();
}
public Repository(DatabaseContext context)
{
_context = context;
}
public void Add(T obj)
{
_context.Set<T>().Add(obj);
}
public void Delete(T entity)
{
_context.Set<T>().Remove(entity);
}
public async Task<IEnumerable<T>> GetAll()
{
return await _context.Set<T>().ToListAsync();
}
public async Task<T> GetById(object id)
{
return await _context.Set<T>().FindAsync(id);
}
public void Update(T obj)
{
_context.Set<T>().Update(obj);
}
public async Task<bool> Save()
{
try
{
await _context.SaveChangesAsync();
}
catch (Exception)
{
return false;
}
return true;
}
}
EDIT
I should mention that EmailAddress was added to the database via EF migration.
I've Created an EF core 2.0 application and trying to validate the model on Savechanges but its only returning the first validation error.
Here are my Dbcontext and controller
public partial class ProductWarehouseContext : DbContext
{ public List<string> ErrorList=new List<string>();
public ProductWarehouseContext(DbContextOptions<ProductWarehouseContext> options)
: base(options)
{
}
public virtual DbSet<Customer> Customer { get; set; }
public virtual DbSet<Order> Order { get; set; }
public virtual DbSet<OrderItem> OrderItem { get; set; }
public virtual DbSet<Product> Product { get; set; }
public virtual DbSet<Supplier> Supplier { get; set; }
public override int SaveChanges()
{
var entities = from e in ChangeTracker.Entries()
where e.State == EntityState.Added
|| e.State == EntityState.Modified
select e.Entity;
foreach (var entity in entities)
{
var validationContext = new ValidationContext(entity);
Validator.ValidateObject(
entity,
validationContext,
validateAllProperties: true);
}
return base.SaveChanges();}
}
Controller
[HttpPost]
public IActionResult Save([FromBody]CustomerViewModel customer)
{
using (var cont = _context.Database.BeginTransaction())
{
try
{
var cust = new Customer()
{
FirstName = customer.FirstName,
LastName = customer.LastName,
City = customer.City,
Country = customer.Country,
Phone = customer.Phone,
IsSubscribedforAlerts = customer.IsSubscribedforAlerts
};
_context.Customer.Add(cust);
_context.SaveChanges();
cont.Commit();
}
catch (Exception e)
{
Errors.Add(e.Message);
cont.Rollback();
foreach (var err in Errors)
{
ModelState.AddModelError("errors", err);
}
return Ok(ModelState);
}
}
return Ok();
}
Class
public partial class Customer
{
public Customer()
{
Order = new HashSet<Order>();
}
public int Id { get; set; }
[Required(ErrorMessage = "FirstName is required to save a new customer")]
public string FirstName { get; set; }
[Required(ErrorMessage = "LastName is required to save a new customer")]
public string LastName { get; set; }
public string City { get; set; }
public string Country { get; set; }
[Required(ErrorMessage = "PhoneNumber is required to save a new customer")]
public string Phone { get; set; }
public bool? IsSubscribedforAlerts { get; set; }
public ICollection<Order> Order { get; set; }
}
and error is only returnig ""firstname" is required and if I pass the firstname in request object then its returning "lastname" is required.
What should I do to return all the errors how we do it in EF6 using DbEntityValidationException ?
That's because ValidateObject() throws upon first encountering an error. Try using TryValidateObject() instead, and pass it a List<ValidationResult> that accumulate all errors.
Something like:
public class EntityValidationException : Exception
{
public EntityValidationException(IEnumerable<ValidationException> exceptions)
{
this.ValidationErrors = exceptions;
}
public IEnumerable<ValidationException> ValidationErrors { get; }
}
Then in your SaveChanges():
foreach (var entity in entities)
{
var validationContext = new ValidationContext(entity);
var validationResults = new List<ValidationResult>();
Validator.TryValidateObject(entity, validationContext, validationResults);
if (validationResults.Any())
throw new EntityValidationException(validationResults.Select(x => new ValidationException(x, null, null)));
}
Then in your controller/action, you can explicitly handle EntityValidationException:
catch (EntityValidationException validationException)
{
foreach (var err in validationException.ValidationErrors)
{
var validationResult = err.ValidationResult;
ModelState.AddModelError(validationResult.MemberNames.First(), validationResult.ErrorMessage);
}
}
I have tow models Context and Connection as following:
public class Context
{
[Key]
public long ContextId { get; set; }
[Required]
public string Role { get; set; }
public ICollection<Connection> Connections { get; set; }
public Context()
{
}
}
And
public class Connection
{
[Key]
public long ConnectionId { get; set; }
[Required]
public string Name { get; set; }
public long ContextId { get; set; }
public Context Context { get; set; }
public Connection()
{
}
}
So far, I did not create any controller or repository for Connection. ContextRepositiry looks like following:
public class ContextRepository: IContextRepository
{
private readonly WebAPIDataContext _db;
public ContextRepository(WebAPIDataContext db)
{
_db = db;
}
public Context CreateContext(Context context)
{
_db.Contexts.Add(context);
_db.SaveChanges();
return context;
}
public void DeleteContext(long id)
{
Context context = GetContext(id);
if (context != null)
{
_db.Contexts.Remove(context);
_db.SaveChanges();
}
}
public List<Context> GetAllContexts()
{
return _db.Contexts.AsNoTracking().ToList();
}
public Context GetContext(long id)
{
return _db.Contexts.FirstOrDefault(o => o.ContextId == id);
}
public void UpdateContext(long id, Context context)
{
}
}
public interface IContextRepository
{
List<Context> GetAllContexts();
Context GetContext(long id);
Context CreateContext(Context context);
void UpdateContext(long id, Context context);
void DeleteContext(long id);
}
And it's controller:
[Route("api/[controller]")]
public class ContextController : Controller
{
private readonly IContextRepository _contexts;
public ContextController(IContextRepository contexts)
{
_contexts = contexts;
}
[HttpGet("")]
public IActionResult GetAllContexts()
{
try
{
List<Context> contexts = _contexts.GetAllContexts();
return Ok(contexts);
}
catch (EntityNotFoundException<Context>)
{
return NotFound();
}
}
[HttpGet("{id}")]
public IActionResult GetContext(long id)
{
Context context= _contexts.GetContext(id);
if (context == null)
{
return NotFound();
}
return Ok(context);
}
[HttpPost]
public IActionResult CreateContext([FromBody] Context context)
{
if (ModelState.IsValid == false)
{
return BadRequest(ModelState);
}
Context createdContext= _contexts.CreateContext(context);
if (createdContext== null)
{
return NotFound();
}
return CreatedAtAction(
nameof(GetContext), new { id = createdContext.ContextId}, createdContext);
}
[HttpPut("{id}")]
public IActionResult UpdateContext(long id, [FromBody] Context context)
{
if (ModelState.IsValid == false)
{
return BadRequest(ModelState);
}
try
{
_contexts.UpdateContext(id, context);
return Ok();
}
catch (EntityNotFoundException<Context>)
{
return NotFound();
}
}
[HttpDelete("{id}")]
public IActionResult DeleteCOntext(long id)
{
_contexts.DeleteContext(id);
return Ok();
}
}
Question: While creating a context I shouldn't have to enter any connection data i.e. it should be optional (look ta the swagger request bellow). However, on updating a specific context there could be connection data, and corresponding context should be updated accordingly.
Right now, in Swagger for POST if I enter something like:
{
"contextId": 0,
"role": "Employee",
"connections": [
{
"connectionId": 0,
"name": "",
"contextId": 0,
"context": {}
}
]
}
then it says, The Name field is required and The Role field is required (I am trying to send just context data like role and leaving blank connection data- which should be possible). If I remove "connections":[] then it posts with connections set to null, but don't want to remove it from there.