I have a class that I created where a property is another class I wrote. I am being warned that my property is non-nullable and I don't understand why. Aren't all properties of nullable classes nullable?
public class Yeast
{
public int? Id { get; set; }
public Code Brand { get; set; }
public Code Style { get; set; }
public string? Trademark { get; set; }
public int? TempMin { get; set; }
public int? TempMax { get; set; }
public double? Alcohol { get; set; }
public string? Note { get; set; }
}
/// <inheritdoc cref="ICode"/>
public class Code : ICode
{
/// <inheritdoc cref="ICode.Id"/>
public int? Id { get; set; }
/// <inheritdoc cref="ICode.ParentId"/>
public int? ParentId { get; set; }
/// <inheritdoc cref="ICode.Literal"/>
public string? Literal { get; set; }
/// <inheritdoc cref="ICode.Enabled"/>
public bool? Enabled { get; set; }
/// <inheritdoc cref="ICode.Description"/>
public string? Description { get; set; }
}
public interface ICode
{
/// <summary>
/// Code Unique Identifier
/// </summary>
int? Id { get; set; }
/// <summary>
/// Code Foreign Key
/// </summary>
/// <remarks>Optional</remarks>
int? ParentId { get; set; }
/// <summary>
/// Literal Name of Code
/// </summary>
string? Literal { get; set; }
/// <summary>
/// Description of Code
/// </summary>
string? Description { get; set; }
/// <summary>
/// Enabled for Use
/// </summary>
bool? Enabled { get; set; }
}
The issue here is that if you do new Yeast().Brand.Id you'll get a NullReferenceException because Brand is null - but you declared it wouldn't be.
So either the constructor needs to set Brand to a non-null Code value, or you need to mark it as nullable so the compiler can flag it in the consuming code (i.e. say that new Yeast().Brand needs to handle the possibility of a null value).
Related
This's my controller code:
[HttpGet]
[Route()]
public async Task<List<GetCategoryTreeOutputDto>> GetDatasetCategoryTreeAsync([FromUri(Name = "")] GetCategoryTreeInputDto input)
{
return await _category.GetDatasetCategoryTreeAsync(input);
}
public class GetCategoryTreeInputDto
{
/// <summary>
/// 名称
/// </summary>
public string Name { get; set; }
public int? ParentId { get; set; }
}
and I get an error:
When I assign a parameter value,it works,So I have to give a value to use it?But these parameters don't always need to be assigned value.
i assigned value,it works
I'm trying to replicate a view inside EF. The original view used a UNION operator so have split my initial query here in tow to better match. Having some issues working out my syntax. I am trying to query the groups, get their primary contact details. Also get all vehicles and their linked groups. I believe I have specified the ContactLink requirement correctly in the first query.
[BindProperty]
public IList<OrgChartNode> OrgChartNodes { get; set; }
public JsonResult OnGet(string OrgCode)
{
IList<OrgChartNode> OrgChartGroups = _db.Groups
.Include(g => g.ContactLinks)
.ThenInclude(gtc => gtc.Contact)
.Include(g => g.Organisation)
.Where(g => g.OrgCode.Equals(OrgCode))
.Where(g => g.ContactLinks.Any(cl => cl.LinkTypeId == 1))
.Select(g => new OrgChartNode
{
Id = g.Id,
Name = g.Name,
TierId = g.TierId,
ParentGroupId = g.ParentGroupId,
OrgName = g.Organisation.Name,
OrgCode = g.OrgCode,
ContactName = g.ContactLinks.**Contact**.Name,
ContactEmail = g.ContactLinks.**Contact**.Phone,
ContactPhone = g.ContactLinks.**Contact**.Email,
ContactId = g.ContactLinks.**Contact**.ContactId,
})
.OrderByDescending(g => g.TierId)
.ThenBy(g => g.Name)
.AsNoTracking()
.ToList();
IList<OrgChartNode> OrgChartUnits = _db.Units
.Include(u => u.GroupLinks)
.Include(u => u.Organisation)
.Where(u => u.OrgCode.Equals(OrgCode))
.Select(u => new OrgChartNode
{
Id = u.NodeId,
Name = u.Name,
TierId = 0,
ParentGroupId = u.GroupLinks.**GroupId**,
OrgName = u.Organisation.Name,
OrgCode = u.OrgCode,
ContactName = "",
ContactEmail = "",
ContactPhone = "",
ContactId = 0,
})
.OrderBy(u => u.Name)
.AsNoTracking()
.ToList();
OrgChartNodes = OrgChartGroups.Concat(OrgChartUnits)
.ToList();
return new JsonResult(OrgChartNodes);
}
The four Contact fields have been marked wih **. They have red intellisense lines in Visual Studio. Looks like it cat follow to Contact, despite it being ThenInclude() above. So does the GroupId in the second query. Hovering over the acronym/aliases tells me they appear to be the correct classes.
Listed below are the three data classes. You can see the Navigation properties. Are they configured correctly?
How can I include the contact details in my .Select() call?
Group.cs
[Table("Report_Group")]
public class Group
{
[Key, Required, Column("GroupId")]
public int Id { get; set; }
[Required, MaxLength(5)]
public string OrgCode { get; set; }
[Required, MaxLength(100)]
public string Name { get; set; }
public int TierId { get; set; }
public int? ParentGroupId { get; set; }
public int? CostCenter { get; set; }
[Required]
public int ExcludeFromAlertStats { get; set; }
[Required]
public int GroupTypeId { get; set; }
[ForeignKey("ParentGroupId")]
public virtual Group Parent { get; set; }
[ForeignKey("OrgCode")]
public virtual Organisation Organisation { get; set; }
[ForeignKey("TierId")]
public virtual Tier Tier { get; set; }
[ForeignKey("GroupTypeId")]
public virtual GroupType GroupType { get; set; }
[InverseProperty("GroupId")]
public virtual IList<GroupToUnitLink> UnitLinks { get; set; }
[InverseProperty("GroupId")]
public virtual IList<GroupToContactLink> ContactLinks { get; set; }
}
GroupToContactLink.cs
This classes key is set using fluent in OnModelCreating() as it is a composite key.
[Table("Report_Link_Group_to_Contact")]
public class GroupToContactLink
{
public GroupToContactLink()
{
}
public GroupToContactLink(int contactId, int groupId, int linkTypeId)
{
this.ContactId = contactId;
this.GroupId = groupId;
this.LinkTypeId = linkTypeId;
}
[Required]
public int ContactId { get; set; }
[Required]
public int GroupId { get; set; }
[Required]
public int LinkTypeId { get; set; }
[ForeignKey("ContactId")]
public virtual Contact Contact { get; set; }
[ForeignKey("GroupId")]
public virtual Group Group { get; set; }
[ForeignKey("LinkTypeId")]
public virtual ContactLinkType LinkType { get; set; }
}
Contact.cs
[Table("Report_Contact")]
public class Contact
{
/// <summary>
/// Primary Key for Contact in the database
/// </summary>
[Key, Column("ContactId")]
public int Id { get; set; }
/// <summary>
/// Foreign Key indicating <see cref="Data.Organisation"/>
/// </summary>
[Required, StringLength(5)]
public string OrgCode { get; set; }
/// <summary>
/// Name of Contact
/// </summary>
[Required, StringLength(100)]
public string Name { get; set; }
/// <summary>
/// Phone number of contact. Needs to be in +614 format for SMS to work
/// </summary>
[StringLength(12)]
public string Phone { get; set; }
/// <summary>
/// Email Address for Contact
/// </summary>
[StringLength(255), EmailAddress]
public string Email { get; set; }
/// <summary>
/// Navigation property to <see cref="Data.Organisation"/>
/// </summary>
[ForeignKey("OrgCode")]
public virtual Organisation Organisation { get; set; }
[InverseProperty("ContactId")]
public virtual IList<GroupToContactLink> GroupLinks { get; set; }
}
First time I can add Allergies into my DB without a problem is As below screen.
But when I try to add 2nd record (after save the first record) then it gives below mentioned run time exception (is as below screen).
Run time Exception
An error occurred while saving entities that do not expose foreign key
properties for their relationships. The EntityEntries property will
return null because a single entity cannot be identified as the source
of the exception. Handling of exceptions while saving can be made
easier by exposing foreign key properties in your entity types. See
the InnerException for details.
Stack Trace (this is for when I try to add 2nd record for medical table.But it is same for Allergies Table also)
Violation of PRIMARY KEY constraint 'PK__Medicati__3214EC0768A0EA12'.
Cannot insert duplicate key in object 'dbo.Medications'. The statement
has been terminated.
Action Method
[HttpPost]
public ActionResult EditMedicalInfo(string providerKey, string ownerKey, string petKey)
{
var pet = Repository.GetPet(ownerKey, petKey);
if (TryUpdateModel(pet))
{
Repository.Save();
}
var url = Url.AbsoluteRouteUrl("PetDetail", new { controller = "customers", action = "detail", providerKey = providerKey, ownerKey = ownerKey, petKey = petKey }) + "#medical";
return Redirect(url);
}
Pet Model
public class Pet {
public Pet() { Id = Guid.NewGuid(); Created = DateTime.Now; }
public Guid Id { get; set; }
public virtual Owner Owner { get; set; }
[StringLength(50), Required]
public string Name { get; set; }
public string Key { get; set; }
public DateTime Created { get; set; }
[Display(Name = "Birth Date"), DataType(DataType.Date)]
public DateTime? BirthDate { get; set; }
[EnumDataType(typeof(PetType)), UIHint("EnumerationList")]
[Required]
public int Type { get; set; }
[Required]
public Guid BreedId { get; set; }
[Display(Name = "Breed"), ForeignKey("BreedId")]
public virtual Breed Breed { get; set; }
[EnumDataType(typeof(Gender)), UIHint("EnumerationList")]
[Required]
public int? Gender { get; set; }
public double Weight { get; set; }
[Display(Name = "License #")]
public string LicenseNumber { get; set; }
[Display(Name = "Microchip #")]
public string MicrochipNumber { get; set; }
public int? AgeValue { get { return (BirthDate.HasValue) ? (int)(DateTime.Today - BirthDate.Value).TotalDays : default(int?); } }
public string Age { get { return (BirthDate.HasValue) ? BirthDate.Value.ToAge() : "Unknown"; } }
public virtual ICollection<PetPhoto> Photos { get; set; }
public virtual ICollection<Appointment> Appointments { get; set; }
public virtual ICollection<MedicalRecordOrder> Orders { get; set; }
public virtual ICollection<PetDocument> Documents { get; set; }
public virtual ICollection<PetNote> Notes { get; set; }
public virtual ICollection<PetProvider> Providers { get; set; }
public virtual ICollection<PetService> PetServices { get; set; }
public Guid? Avatar { get; set; }
public virtual MedicalRecord Medical { get; set; }
public virtual BehavioralRecord Behavioral { get; set; }
public virtual DietRecord Diet { get; set; }
public Guid? EmergencyVeterinarianId { get; set; }
[ForeignKey("EmergencyVeterinarianId")]
public virtual Provider EmergencyVeterinarian { get; set; }
public virtual ICollection<PetContact> Contacts { get; set; }
[EnumDataType(typeof(ProfileCreatorType))]
public int ProfileCreator { get; set; }
[EnumDataType(typeof(PetClassification)), UIHint("EnumerationList")]
public int Classification { get; set; }
[UIHint("InsuranceCarrier")]
public virtual string InsuranceCarrier { get; set; }
// Non persisted extensions
/// <summary>
/// Non Persisted
/// </summary>
[NotMapped]
public List<AppointmentInfo> AppointmentInfos { get; set; }
/// <summary>
/// Non Persisted
/// </summary>
[NotMapped]
public List<AppointmentInfo> SiblingAppointmentInfos { get; set; }
public IList<ReservationRequest> ReservationRequests { get; set; }
[UIHint("QuickList")]
public virtual ICollection<SpecialInstruction> SpecialInstructions { get; set; }
public virtual PetSitterRestrictionPermission PetSitterRestrictionPermission { get; set; }
public virtual PetSitterBehavior PetSitterBehavior { get; set; }
public virtual PetSitterCleaningRecord PetSitterCleaningRecord { get; set; }
public virtual PetSitterNote PetSitterNote { get; set; }
}
Allergy Model
public class Allergy {
public Allergy() { Id = Guid.NewGuid(); }
[ScaffoldColumn(false)]
public Guid Id { get; set; }
public string Name { get; set; }
public string Treatment { get; set; }
}
How could I avoid above error when I try to add 2nd record ?
I'm getting this error some time, without any action I do
This appears at random
I use this frameworks:
Entity in CodeFirst type,Mvc3
Sometimes I get this erros in diffrent data types or for other models:
The 'CatID' property on 'Cat' could not be set to a 'Boolean' value. You must set this property to a non-null value of type 'Int32
or
The 'CatID' property on 'Cat' could not be set to a 'String' value. You must set this property to a non-null value of type 'Int32
my site subject is news publishing and my client operators work with site and insert/edit data During all off day
Edit:
i see that this erros is not for a page,when i have this error,no page in my site not load and all of the pages have this message
my model:
public class SubCatNews
{
[Key]
public int SubCatNewsID { get; set; }
// [EdmScalarPropertyAttribute(IsNullable = true)]
// public int? SubCatID { get; set; }
[Required(ErrorMessage = "some error")]
public string Title { get; set; }
[Required(ErrorMessage = "some error")]
[AllowHtml]
[DataType(DataType.Html)]
public string Summary { get; set; }
[Required(ErrorMessage = "some error")]
[AllowHtml]
[DataType(DataType.Html)]
public string Details { get; set; }
[EdmScalarPropertyAttribute(IsNullable = true)]
public bool? ImpStatus { get; set; }
[EdmScalarPropertyAttribute(IsNullable = true)]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy}")]
public DateTime? Created { get; set; }
[EdmScalarPropertyAttribute(IsNullable = true)]
public bool? Visible { get; set; }
[EdmScalarPropertyAttribute(IsNullable = true)]
public string pic { get; set; }
[EdmScalarPropertyAttribute(IsNullable = true)]
public int? UsersID { get; set; }
[EdmScalarPropertyAttribute(IsNullable = true)]
public int? StatusID { get; set; }
[EdmScalarPropertyAttribute(IsNullable = true)]
public int? NewsTypeID { get; set; }
[EdmScalarPropertyAttribute(IsNullable = true)]
public int? ZonesID { get; set; }
[EdmScalarPropertyAttribute(IsNullable = true)]
public int? lanID { get; set; }
//public int RatingSubCatNewsID { get; set; }
public virtual Users Users { get; set; }
// public virtual SubCat SubCat { get; set; }
public virtual NewsStatus Status { get; set; }
public virtual NewsType NewsType { get; set; }
public virtual ICollection<SubCatNewsComment> SubCatNewsComments { get; set; }
public virtual ICollection<NewsInSubCat> NewsInSubCatss { get; set; }
public virtual ICollection<SubNewsInTag> SubNewsInTags { get; set; }
//public virtual RatingSubCatNews RatingSubCatNews { get; set; }
}
But i`m wondering that when i make any change in web.config,site is up!
i thing this is for caching data and values in Entity
my Context Creator:
public abstract class BaseController<TEntityType, TIdType> : ContextGridController<HNewsPortalContext, TEntityType, TIdType>
where TEntityType : class
{
protected override HNewsPortalContext CreateContext()
{
return new HNewsPortalContext();
}
}
before this time,my Context Creator,return Context like this:
HNewsPortalContext.Singleton;
i guess this was for static context and entity caching make this error,but newing context,do not fix my error
now when my site have this error,i make a little change(switch Custom Error Mode value between Off or RemoteOnly) in web.config and save it,then site is up
please help me
tanx
my full error message:
full message image
full message image
Attach debugger, break on exception and check the stack trace to see what code is setting your properties.
i checked and see that was because overflowing my application pool
my site was on a shared server and session expire time was very long
finish
I have tried to debug and find where the mismatch is coming from but I can not. Any ideas about where to look?
here is the model
public class PatientModel : BaseNopEntityModel
{
public PatientModel()
{
AvailableStates = new List<SelectListItem>();
}
[NopResourceDisplayName("Patient.Fields.FirstName")]
[AllowHtml]
public string FirstName { get; set; }
[NopResourceDisplayName("Patient.Fields.LastName")]
[AllowHtml]
public string LastName { get; set; }
[NopResourceDisplayName("Patient.Fields.MiddleName")]
[AllowHtml]
public string MiddleName { get; set; }
[NopResourceDisplayName("Patient.Fields.RoomNumber")]
[AllowHtml]
public string RoomNumber { get; set; }
[NopResourceDisplayName("Patient.Fields.HospitalName")]
[AllowHtml]
public string HospitalName { get; set; }
[NopResourceDisplayName("Patient.Fields.StateProvince")]
public int? StateProvinceId { get; set; }
[NopResourceDisplayName("Patient.Fields.StateProvince")]
[AllowHtml]
public string StateProvince { get; set; }
[NopResourceDisplayName("Patient.Fields.City")]
[AllowHtml]
public string City { get; set; }
[NopResourceDisplayName("Patient.Fields.ZipPostalCode")]
[AllowHtml]
public string ZipPostalCode { get; set; }
public IList<SelectListItem> AvailableStates { get; set; }
public bool FirstNameDisabled { get; set; }
public bool LastNameDisabled { get; set; }
public bool MiddleNameDisabled { get; set; }
public bool RoomNumberDisabled { get; set; }
public bool HospitalNameDisabled { get; set; }
public bool StateProvinceDisabled { get; set; }
public bool CityDisabled { get; set; }
public bool ZipPostalCodeDisabled { get; set; }
}
and here is the entity that it is trying to map to
public class Patient : BaseEntity, ICloneable
{
/// <summary>
/// Gets or sets the first name
/// </summary>
public virtual string FirstName { get; set; }
/// <summary>
/// Gets or sets the last name
/// </summary>
public virtual string LastName { get; set; }
/// <summary>
/// Gets or sets the middle name
/// </summary>
public virtual string MiddleName { get; set; }
/// <summary>
/// Gets or sets the patient room number
/// </summary>
public virtual string RoomNumber { get; set; }
public virtual string HospitalName { get; set; }
/// <summary>
/// Gets or sets the state/province identifier
/// </summary>
public virtual int? StateProvinceId { get; set; }
/// <summary>
/// Gets or sets the state/province
/// </summary>
public virtual StateProvince StateProvince { get; set; }
/// <summary>
/// Gets or sets the city
/// </summary>
public virtual string City { get; set; }
/// <summary>
/// Gets or sets the zip/postal code
/// </summary>
public virtual string ZipPostalCode { get; set; }
public virtual DateTime CreatedOnUtc { get; set; }
public object Clone()
{
var pat = new Patient()
{
FirstName = this.FirstName,
LastName = this.LastName,
MiddleName = this.MiddleName,
RoomNumber = this.RoomNumber,
HospitalName = this.HospitalName,
StateProvince = this.StateProvince,
StateProvinceId = this.StateProvinceId,
City = this.City,
ZipPostalCode = this.ZipPostalCode,
CreatedOnUtc = DateTime.UtcNow
};
return pat;
}
}
and mapper where the issue occurs
public static PatientModel ToModel(this Patient entity)
{
return Mapper.Map<Patient, PatientModel>(entity);
}
That means you never called Mapper.CreateMap<>() for those two types.
I found a way of getting it to work correctly the only problem was I had to change
public static PatientModel ToModel(this Patient entity)
{
return Mapper.Map<Patient, PatientModel>(entity);
}
and remove the mapper and do it manually to map the patient entitiy to the model.