URL routing ASP Core MVC - asp.net

I have 2 Models. Organization and Site. A org can have many sites but a site can only have 1 org. I have been able to successfully create a page that you can create an org with its primary site and all saves fine into the database.
What id like to do is have a page that shows all the sites for an organization. Id like the url to be something like ~/Organizations/6/Sites. and to see info on a specific site, the url should read ~/organizations/6/sites/2
How would i go about achieving this? Can anyone point me in the right direction. My understanding is that it would be done within the endpoints.MapControllerRoute section under the startup.cs file.
Below are the 2 models and the view action for the org and the viewsites action for the sites which currently both reside in the orgcontroller
public class Organization:BaseEntity
{
[Required]
[Display(Name = "Name")]
public string Name { get; set; }
[Display(Name = "Logo")]
public string Logo { get; set; }
[Required]
[Display(Name = "Type")]
public OrganizationType Type { get; set; }
[DataType(DataType.DateTime)]
public DateTime CreatedDate { get; set; }
[DataType(DataType.DateTime)]
public DateTime ModifiedDate { get; set; }
public int Demo { get; set; }
[Required]
public bool Active { get; set; }
public virtual ICollection<Contact> Contacts { get; set; }
public virtual ICollection<Site> Sites { get; set; }
}
public class Site : BaseEntity
{
[Required]
[Display(Name = "Name")]
public string Name { get; set; }
[Display(Name = "Address")]
public string FullAddress
{
get
{
return StreetNumber + " " + StreetAddress + " " + Suburb + " " + State + " " + PostCode + " " + Country;
}
}
[Required]
[Display(Name = "Street Number")]
public string StreetNumber { get; set; }
[Required]
[Display(Name = "Street Address")]
public string StreetAddress { get; set; }
[Required]
[DataType(DataType.PostalCode)]
[Display(Name = "Postcode")]
public string PostCode { get; set; }
[Required]
[Display(Name = "Suburb")]
public string Suburb { get; set; }
[Required]
[Display(Name = "State")]
public string State { get; set; }
[Required]
[Display(Name = "Country")]
public string Country { get; set; }
[Required]
[DataType(DataType.PhoneNumber)]
[Display(Name = "Phone Number")]
public string PhoneNumber { get; set; }
[DataType(DataType.DateTime)]
public DateTime CreatedDate { get; set; }
[DataType(DataType.DateTime)]
public DateTime ModifiedDate { get; set; }
[Required]
public bool IsPrimary { get; set; }
public int Demo { get; set; }
[Required]
public bool Active { get; set; }
[Display(Name = "Image")]
public string Image { get; set; }
public virtual Organization Organization { get; set; }
}
// GET: Organizations/View/5
public async Task<IActionResult> View(Guid? id)
{
if (id == null)
{
return NotFound();
}
var organization = _context.Organizations.Include("Sites").Include("Contacts").FirstOrDefault(x=> x.ID == id);
ViewBag.SiteCount = organization.Sites.Count;
ViewBag.ContactCount = organization.Contacts.Count;
if (organization == null)
{
return NotFound();
}
return View(organization);
}
// GET: Organizations/View/5
public async Task<IActionResult> ViewSites(Guid? id)
{
if (id == null)
{
return NotFound();
}
List<Site> sites = _context.Organizations.Include("Sites").Where(x=>x.ID == id).ToList().FirstOrDefault().Sites.ToList();
return View(sites);
}

Here is a working demo like below:
Model:
public class BaseEntity
{
public Guid Id { get; set; }
}
public class Organization : BaseEntity
{
[Required]
[Display(Name = "Name")]
public string Name { get; set; }
[Display(Name = "Logo")]
public string Logo { get; set; }
[DataType(DataType.DateTime)]
public DateTime CreatedDate { get; set; }
[DataType(DataType.DateTime)]
public DateTime ModifiedDate { get; set; }
public int Demo { get; set; }
[Required]
public bool Active { get; set; }
public virtual ICollection<Site> Sites { get; set; }
}
public class Site : BaseEntity
{
[Required]
[Display(Name = "Name")]
public string Name { get; set; }
[Display(Name = "Address")]
public string FullAddress
{
get
{
return StreetNumber + " " + StreetAddress + " " + Suburb + " " + State + " " + PostCode + " " + Country;
}
}
[Required]
[Display(Name = "Street Number")]
public string StreetNumber { get; set; }
[Required]
[Display(Name = "Street Address")]
public string StreetAddress { get; set; }
[Required]
[DataType(DataType.PostalCode)]
[Display(Name = "Postcode")]
public string PostCode { get; set; }
[Required]
[Display(Name = "Suburb")]
public string Suburb { get; set; }
[Required]
[Display(Name = "State")]
public string State { get; set; }
[Required]
[Display(Name = "Country")]
public string Country { get; set; }
[Required]
[DataType(DataType.PhoneNumber)]
[Display(Name = "Phone Number")]
public string PhoneNumber { get; set; }
[DataType(DataType.DateTime)]
public DateTime CreatedDate { get; set; }
[DataType(DataType.DateTime)]
public DateTime ModifiedDate { get; set; }
[Required]
public bool IsPrimary { get; set; }
public int Demo { get; set; }
[Required]
public bool Active { get; set; }
[Display(Name = "Image")]
public string Image { get; set; }
public virtual Organization Organization { get; set; }
}
Controller:
public class OrganizationsController : Controller
{
private readonly YourDbContext _context;
public OrganizationsController(YourDbContext context)
{
_context = context;
}
// GET: Organizations/Details/5
public async Task<IActionResult> Details(Guid? id,Guid siteId )
{
if (id == null)
{
return NotFound();
}
var organization = await _context.Organization.Include(o=>o.Sites)
.FirstOrDefaultAsync(m => m.Id == id);
var site = organization.Sites.Where(x => x.Id == siteId).FirstOrDefault();
return View(site);
}
}
Startup.cs:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
//...
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}/{siteId?}");
});
}
Result:
Request url: https://localhost:portNumber/Organizations/Details/orgnizationid/siteid.
UPDATE:
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
endpoints.MapControllerRoute(
name: "custom",
pattern: "Organizations/{id?}/{sites}/{siteId?}",
defaults: new { controller = "Organizations", action = "Details" });
});
Or a simple way is to use route attribute:
[Route("[controller]/{id}/sites/{siteId}")]
public async Task<IActionResult> Details(Guid id,Guid? siteId )

The way ive done it in the end is
Controller
// GET: Organizations/5
// GET: Organizations
[Route("[controller]/{id?}")]
public async Task<IActionResult> View(int? id)
{
if (id == 0)
{
return NotFound();
}
if (id == null)
{
return View("ViewAll",await _context.Organizations.Include("Sites").Include("Contacts").ToListAsync());
}
var organization = _context.Organizations.Include("Sites").Include("Contacts").FirstOrDefault(x=> x.ID == id);
if (organization == null)
{
return NotFound();
}
return View("View",organization);
}
// GET: Organizations/5/Sites/2
// GET: Organizations/5/Sites
// GET: Organizations/5
[Route("[controller]/{id}/sites/{siteId?}")]
public async Task<IActionResult> ViewSites(int ordId, int? siteId)
{
if (ordId == 0)
{
return NotFound();
}
if (siteId == 0)
{
List<Site> sites = _context.Organizations.Include("Sites").Where(x => x.ID == ordId).ToList().FirstOrDefault().Sites.ToList();
return View("ViewSites",sites);
}
Site site = _context.Organizations.Include("Sites").Where(x => x.ID == ordId).ToList().FirstOrDefault().Sites.ToList().Where(y=>y.ID == siteId).FirstOrDefault();
return View("ViewSite", site);
}
Startup.cs
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "OrgSites",
pattern: "Organizations/{id}/{sites}/{siteId?}",
defaults: new { controller = "Organizations", action = "ViewSites" });
endpoints.MapControllerRoute(
name: "Orgs",
pattern: "Organizations/{id?}",
defaults: new { controller = "Organizations", action = "View" });
endpoints.MapControllerRoute(
name: "Orgs",
pattern: "Organizations",
defaults: new { controller = "Organizations", action = "View" });
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
endpoints.MapRazorPages();
});

Related

Automapper missing type map configuration or unsupported mapping error

I am using Auto mapper and I am getting this error, I am getting this error within AddAsync() method. Please help me out to solve this issue.
Missing type map configuration or unsupported mapping.\r\n\r\nMapping types:\r\nDepartmentsViewModel -> Departments\r\nEmployeeAttendanceApp.ViewModels.DepartmentsViewModel -> EmployeeAttendanceApp.Models.StaffManagement.Departments
My class
public interface IMapperConfig
{
IMapper CreateMapper();
}
public class MapperConfig : IMapperConfig
{
public IMapper CreateMapper()
{
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<RegisterStaffs, RegisterStaffViewModel>();
cfg.CreateMap<AttendanceRecorder, AttendanceRecorderViewModel>();
cfg.CreateMap<ManageLeaves, ManageLeavesViewModel>();
cfg.CreateMap<RegisterDevices, RegisterDevicesViewModel>();
cfg.CreateMap<Departments, DepartmentsViewModel>();
});
return config.CreateMapper();
}
}
public class DepartmentsViewModel
{
[Key]
public int DepartmentId { get; set; }
[DisplayName("اسم القسم/ الادارة")]
[Required(ErrorMessage = "الرجاء ادخال اسم القسم")]
public string DepartmentName { get; set; }
[DisplayName("اضافة ملاحظات القسم")]
public string Remarks { get; set; }
public bool? IsUpdated { get; set; }
public bool? IsDeleted { get; set; }
public string CreatedBy { get; set; }
public string DeletedBy { get; set; }
public string UpdatedBy { get; set; }
[DisplayName("عدد الموظفيين")]
[Required(ErrorMessage = " الرحاء إدخال عدد موظفيين القسم")]
public long? StaffNumber { get; set; }
public DateTime? CreatedDate { get; set; }
public virtual ICollection<RegisterDevicesViewModel> RegisterDevices { get; set; }
public virtual ICollection<RegisterStaffViewModel> RegisterStaffs { get; set; }
}
public partial class Departments
{
[Key]
public int DepartmentId { get; set; }
public string DepartmentName { get; set; }
public string Remarks { get; set; }
public bool? IsUpdated { get; set; }
public bool? IsDeleted { get; set; }
public string CreatedBy { get; set; }
public string DeletedBy { get; set; }
public string UpdatedBy { get; set; }
public long? StaffNumber { get; set; }
public DateTime? CreatedDate { get; set; }
public virtual ICollection<RegisterDevices> RegisterDevices { get; set; }
public virtual ICollection<RegisterStaffs> RegisterStaffs { get; set; }
}
**I am getting the error in this method**
public async Task<bool> AddAsync(DepartmentsViewModel departmentsView)
{
try
{
var department = mapper.Map<DepartmentsViewModel, Departments>(departmentsView);
await context.Departments.AddAsync(department);
await context.SaveChangesAsync();
return true;
}
catch(Exception ex)
{
logger.LogError(ex, ex.Message);
return false;
}
}
//here is startup file where I have registered the services
services.AddSingleton<IMapperConfig, MapperConfig>();
services.AddTransient<IDepartmentManager, DepartmentManager>();
I have resolved this issue by adding .ReverseMap() inside MapperConfig class
cfg.CreateMap<Departments, DepartmentsViewModel>().ReverseMap();
but still I can't understand why it didn't work previously with out it because I have seen various examples never using ReverseMap()

Can't convert from model to viewmodel, using AutoMapper asp.net core

I am using Auto mapper to map between modelviews and models. I have followed the same steps given by the Auto mapper documentation and still can't find where the issue is.
public class RegisterStaffViewModel
{
public int Id { get; set; }
[Required(ErrorMessage = "StaffName Required")]
public string StaffName { get; set; }
[Required(ErrorMessage = "Gender Required")]
public string Gender { get; set; }
[Required(ErrorMessage = "Address Required")]
public string Address { get; set; }
[Required(ErrorMessage = "StaffCode Required")]
public string StaffCode { get; set; }
[DisplayName("Department")]
[Required(ErrorMessage = "Department is Required")]
public int? DepartmentId { get; set; }
public string CardNo { get; set; }
[Required(ErrorMessage = "Mobileno Required")]
[RegularExpression(#"^(\d{10})$", ErrorMessage = "Wrong Mobileno")]
public string MobileNo { get; set; }
[Required(ErrorMessage = "EmailID Required")]
[RegularExpression(#"^([a-zA-Z0-9_\-\.]+)#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$", ErrorMessage = "Please enter a valid e-mail adress")]
public string Email { get; set; }
public DateTime EntryDate { get; set; }
[Display(Name = "Position")]
[Required(ErrorMessage = "Position is Required")]
public int? PositionId { get; set; }
[Display(Name = "Staff Type")]
[Required(ErrorMessage = "Staff Type is Required")]
public int? StaffTypeId { get; set; }
public string CardIdNo { get; set; }
public bool? IsDeleted { get; set; }
public bool? IsUpdated { get; set; }
public string CreatedBy { get; set; }
public string UpdatedBy { get; set; }
public string DeletedBy { get; set; }
public string Remarks { get; set; }
public virtual ApplicationUser CreatedByNavigation { get; set; }
public virtual ApplicationUser DeletedByNavigation { get; set; }
public virtual Departments Department { get; set; }
public virtual Positions Position { get; set; }
public virtual StaffTypes StaffType { get; set; }
public virtual ApplicationUser UpdatedByNavigation { get; set; }
public virtual ICollection<AttendanceRecorderViewModel> AttendanceRecorder { get; set; }
public virtual ICollection<ManageLeavesViewModel> ManageLeaves { get; set; }
public virtual ICollection<RegisterDevicesViewModel> RegisterDevices { get; set; }
}
=============================================================================================
public partial class RegisterStaffs
{
public int Id { get; set; }
public string StaffName { get; set; }
public string Gender { get; set; }
public string Address { get; set; }
public string StaffCode { get; set; }
public int? DepartmentId { get; set; }
public string CardNo { get; set; }
public string MobileNo { get; set; }
public string Email { get; set; }
public DateTime EntryDate { get; set; }
public int? PositionId { get; set; }
public int? StaffTypeId { get; set; }
public string CardIdNo { get; set; }
public bool? IsDeleted { get; set; }
public bool? IsUpdated { get; set; }
public string CreatedBy { get; set; }
public string UpdatedBy { get; set; }
public string DeletedBy { get; set; }
public string Remarks { get; set; }
public virtual ApplicationUser CreatedByNavigation { get; set; }
public virtual ApplicationUser DeletedByNavigation { get; set; }
public virtual Departments Department { get; set; }
public virtual Positions Position { get; set; }
public virtual StaffTypes StaffType { get; set; }
public virtual ApplicationUser UpdatedByNavigation { get; set; }
public virtual ICollection<AttendanceRecorder> AttendanceRecorder { get; set; }
public virtual ICollection<ManageLeaves> ManageLeaves { get; set; }
public virtual ICollection<RegisterDevices> RegisterDevices { get; set; }
}
============================================================================================
public interface IMapperConfig
{
IMapper CreateMapper();
}
public class MapperConfig : IMapperConfig
{
public IMapper CreateMapper()
{
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<RegisterStaffs, RegisterStaffViewModel>();
cfg.CreateMap<AttendanceRecorder, AttendanceRecorderViewModel>();
cfg.CreateMap<ManageLeaves, ManageLeavesViewModel>();
cfg.CreateMap<RegisterDevices, RegisterDevicesViewModel>();
});
return config.CreateMapper();
}
}
==========================================================================================
public async Task<ReturnResult<List<RegisterStaffViewModel>>> GetAllEmployees()
{
var result = new ReturnResult<List<RegisterStaff>>();
try
{
var employees = await context.RegisterStaffs.Where(x => (bool)!x.IsDeleted).OrderByDescending(x => x.EntryDate).AsNoTracking().ToListAsync();
// **here is the error**
result.Success(mapper.Map<List<RegisterStaffs>, List<RegisterStaffViewModel>>(employees));
}
catch(Exception ex)
{
}
return result;
}
============================================================================================
public class ReturnResult<T>
{
public ReturnResult()
{
ErrorList = new List<string>();
}
public bool IsSuccess { get; set; }
public HttpCode HttpCode { get; set; }
public T Data { get; set; }
public List<string> ErrorList { get; set; }
/// <summary>
/// Set success result with data
/// </summary>
/// <param name="Data"></param>
public void Success(T Data)
{
this.IsSuccess = true;
this.HttpCode = HttpCode.Success;
this.Data = Data;
}
/// <summary>
/// Set Server Error result with error message
/// </summary>
/// <param name="Error"></param>
public void ServerError(string Error)
{
this.IsSuccess = false;
this.HttpCode = HttpCode.ServerError;
this.ErrorList.Add(Error);
}
/// <summary>
/// Set Not Found result with error message
/// </summary>
/// <param name="Error"></param>
public void NotFound(string Error)
{
this.IsSuccess = false;
this.HttpCode = HttpCode.NotFound;
this.ErrorList.Add(Error);
}
}
I found the issue was here
var result = new ReturnResult<List<RegisterStaff>>();
i have changed it to
var result = new ReturnResult<List<RegisterStaffViewModel>>();

How to create a drop-down in asp.net core MVC from another Model with validation?

Model Class.cs
public class Class
{
public int ClassId { get; set; }
[NotMapped]
public string EncryptedId { get; set; }
[Required]
[Display(Name = "Class Name")]
public string ClassName { get; set; }
}
Model Subject.cs
public class Subject
{
public int SubjectId { get; set; }
[NotMapped]
public string EncryptedId { get; set; }
public string SubjectName { get; set; }
public int ClassId { get; set; }
public Class Class { get; set; }
}
ViewModel CreateSubjectViewModel.cs
public class CreateSubjectViewModel
{
public int SubjectId { get; set; }
[NotMapped]
public string EncryptedId { get; set; }
[Required]
[Display(Name = "Subject Name")]
public string SubjectName { get; set; }
public int ClassId { get; set; }
public int ClassesId { get; set; }
public virtual List<Class> Classes { get; set; }
}
Controller Code
[HttpGet]
public IActionResult CreateSubject()
{
List<Class> classList = _context.Classes.ToList();
ViewData["classList"] = classList.Select(x => new SelectListItem { Value = x.EncryptedId, Text = x.ClassName });
return View();
}
[HttpPost]
public IActionResult CreateSubject(CreateSubjectViewModel model)
{
if (ModelState.IsValid)
{
Subject newSubject = new Subject
{
//SubjectName = model.SubjectName,
//here code for store data in subject table
};
_cdsRepository.AddSubject(newSubject);
return RedirectToAction("ListClasses", "UDP");
}
return View(model);
}
How can I get data from Class.cs and show in drop-down with proper validation of drop-down on button click.
If everything is OK, then store data in Subject.cs with Class Id value.

MVC one to many user companies and notifiaction

I have three tables. Users Notification and Company. I have to made relation one to many which one user can have many notification from company. Notification have to be seen only for users from this company. Example users A company B can see notification only from company B not from the others. How to create query and check user which is actually logged in? Can you help me? I show the code.
[Table("Core.Powiadomienias")]
public class Powiadomienia : Entity
{
public string Tytul { get; set; }
public string Tresc { get; set; }
public long? Firma { get; set; }
public ICollection<User> Users { get; set; }
}
public class User : Entity, IUserIdentity, IAuditable, ILoggable,
IConfidential
{
#region User()
public User()
{
LockoutEnabled = true;
Roles = new List<Role>();
}
#endregion
public Guid PublicId { get; set; }
public DateTime DateCreatedUtc { get; set; }
public DateTime? DateModifiedUtc { get; set; }
public long CreatedBy { get; set; }
public long? ModifiedBy { get; set; }
public string UserName { get; set; }
public string Email { get; set; }
public bool EmailConfirmed { get; set; }
public string PasswordHash { get; set; }
public string SecurityStamp { get; set; }
public string PhoneNumber { get; set; }
public bool PhoneNumberConfirmed { get; set; }
public bool TwoFactorEnabled { get; set; }
public DateTime? LockoutEndDateUtc { get; set; }
public bool LockoutEnabled { get; set; }
public int AccessFailedCount { get; set; }
public bool IsAdmin { get; set; }
public string RolesGroupsXml { get; set; }
public string GivenName { get; set; }
public string Surname { get; set; }
public string JobPosition { get; set; }
public string HomeCity { get; set; }
public string HomeStreet { get; set; }
public string HomeHouseNo { get; set; }
public string HomeFlatNo { get; set; }
public string HomePostCode { get; set; }
public string HomeCountry { get; set; }
public long? FacePictureId { get; set; }
public virtual File FacePicture { get; set; }
public long? FirmaId { get; set; }
public Powiadomienia Powiadomienia { get; set; }
#region GetList()
public static IEnumerable<TResult> GetList<TResult>(IPager pager, string
tytul , string tresc = null, long? firma = null)
{
using (var context = Context.Read())
{
Slave db = new Slave();
var query = context.Query<Powiadomienia>().AsQueryable();
if (!String.IsNullOrEmpty(tytul))
{
query = query.Where(p => p.Tytul.Contains(tytul));
}
if (!String.IsNullOrEmpty(tresc))
{
query = query.Where(p => p.Tresc.Contains(tytul) &&
db.Firmy.Select(x => x.Nazwa).Equals(p.Firma));
}
if (firma.HasValue)
{
var value = String.Format("<item>{0}</item>", firma);
query = query.Where(p => p.Firma.HasValue);
}
return query
.Pager(pager)
.GetResult<TResult>();
}
}
public class UserService
{
#region GetList()
public static IEnumerable<TResult> GetList<TResult>(IPager pager, string
userName = null, string givenName = null, string surname = null, long? role
null, bool? isAdmin = null, long? firmaid = null)
{
using (var context = Context.Read())
{
var query = context.Query<User>().AsQueryable();
if (!String.IsNullOrEmpty(userName))
{
query = query.Where(p => p.UserName.Contains(userName));
}
if (!String.IsNullOrEmpty(givenName))
{
query = query.Where(p => p.GivenName.Contains(givenName));
}
if (!String.IsNullOrEmpty(surname))
{
query = query.Where(p => p.Surname.Contains(surname));
}
if (firmaid.HasValue)
{
var value = String.Format("<item>{0}</item>", firmaid.Value);
query = query.Where(p => p.FirmaId.HasValue);
}
if (isAdmin.HasValue && isAdmin.Value == true)
{
query = query.Where(p => p.IsAdmin == true);
}
return query
.Pager(pager)
.GetResult<TResult>();
}
}
#endregion

ServiceStack, OrmLite Issue Saving Related Entities

I've searched for a while looking for a solution to this problem and haven't found anything.
I'm trying to POST a Client DTO and it's related Contacts DTOs to my ServiceStack web service but I'm getting an error. I've followed along with the OrmLite tests located here.
My DTOs:
public partial class Client {
[AutoIncrement]
public int ID { get; set; }
public string Street { get; set; }
public string City { get; set; }
public string State { get; set; }
public string ZipCode { get; set; }
public decimal? Latitude { get; set; }
public decimal? Longitude { get; set; }
public string HomePhoneAreaCode { get; set; }
public string HomePhoneExchange { get; set; }
public string HomePhoneNumber { get; set; }
public string HomeFaxAreaCode { get; set; }
public string HomeFaxExchange { get; set; }
public string HomeFaxNumber { get; set; }
public string KeyNumber { get; set; }
public string AlarmCode { get; set; }
public string GarageDoorCode { get; set; }
public string MyAPCUsername { get; set; }
public string MyAPCPassword { get; set; }
public bool IsActive { get; set; }
public string Notes { get; set; }
[Reference]
public List<Contact> Contacts { get; set; }
}
public partial class Contact {
[AutoIncrement]
public int ID { get; set; }
public int ClientID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string WorkPhoneAreaCode { get; set; }
public string WorkPhoneExchange { get; set; }
public string WorkPhoneNumber { get; set; }
public string MobilePhoneAreaCode { get; set; }
public string MobilePhoneExchange { get; set; }
public string MobilePhoneNumber { get; set; }
public bool CanSMS { get; set; }
public string PersonalEmail { get; set; }
public string WorkEmail { get; set; }
public string AlternateEmail { get; set; }
public int Ordinal { get; set; }
[Reference]
public Client Client { get; set; }
}
In my Service:
public int Post(Client client) {
Db.Save(client, references: true);
return client.ID;
}
And my test code:
var newClient = new Client {
Street = "1234 Any Avenue",
City = "Gorham",
State = "ME",
ZipCode = "22222",
HomePhoneAreaCode = "123",
HomePhoneExchange = "456",
HomePhoneNumber = "7890",
HomeFaxAreaCode = "098",
HomeFaxExchange = "765",
HomeFaxNumber = "4321",
KeyNumber = "99",
AlarmCode = "1234",
GarageDoorCode = "abcd",
IsActive = true,
Notes = "These are the notes for the new client.",
Contacts = new List<Contact>() {
new Contact { FirstName = "John", LastName = "Doe", PersonalEmail = "john.doe#gmail.com", CanSMS = true, Ordinal = 1 },
new Contact { FirstName = "Jane", LastName = "Smith", PersonalEmail = "jane.smith#gmail.com", CanSMS = false, Ordinal = 2 }
},
};
// POST entity
int newClientID = serviceClient.Post<int>(newClient);
The last line produces the error -
WebServiceException, message "Cant find 'ClientId' Property on Type 'Contact'"
I've tried different combinations of the Reference, References, and ForeignKey attributes to no avail.
Any help would be appreciated.
Thanks,
Jay

Resources