Linq doesn't want to cooperate - DbExpressionBinding error - asp.net-mvc

I am trying to get something from my database, i need it to be like that:
var tribunalCase = context.TribunalCases.Where(c => c.Voters.Any(v => v.Voter.UserName == User.Identity.Name))
.Select(c => c)
.ToList();
But then, it crashes when i try to use .Any() or .All(). I get the following error:
DbExpressionBinding requires an input expression with a collection
ResultType.
Parameter name: input
This is my model:
public class Tribunal
{
public int Id { get; set; }
public Account User { get; set; }
public DateTime Expires { get; set; }
public Thread Thread { get; set; }
public int Points { get; set; }
public String Comment { get; set; }
public int VotersCount { get; set; }
public List<Voters> Voters { get; set; }
}
public class Voters
{
public int Id { get; set; }
public Account Voter { get; set; }
public bool Vote { get; set; }
public Tribunal Tribunal { get; set; }
}
Which i configured like that:
modelBuilder.Entity<Tribunal>()
.HasOptional(t => t.Voters)
.WithRequired();
How can i fix this error?

Configuration is incorrect: Voters is a collection, so you should call HasMany, not HasOptional.

Related

ASP.NET MVC Check if User has already posted in this table

I'm gonna cut to the chase.
I'm creating a Survey platform, it has 3 models.
Model Survey, it has Many SurveyQuestion which has many SurveyAnswer.
(I can insert all of the values of these models but I dont think it is needed)
public class SurveyAnswer
{
[Key]
public int Id { get; set; }
public string Value { get; set; }
public string SubmittedBy { get; set; }
public int SurveyId { get; set; }
public int QuestionId { get; set; }
public virtual Survey Survey { get; set; }
public virtual SurveyQuestion Question { get; set; }
public string Comment { get; set; }
}
Now a problem I'm having is once someone created a survey and another person is starting it, he answers and that's it. How do I show that the next time he comes to an index page? How do I show that "you already submitted this survey"? Do I do that in Controller or in View? I would prefer to that in this action currently (it's a menu for all ongoing surveys).
[HttpGet]
public ActionResult Menu()
{
var survey = Mapper.Map<IEnumerable<Survey>, IEnumerable<SurveyViewModel>>(_unitOfWork.SurveyRepository.Get());
return View(survey.ToList());
}
Put all your validation rules to your AbstractValidator class.
[Validator(typeof(SurveyAnswerValidator))]
public class SurveyAnswer{
[Key]
public int Id { get; set; }
public string Value { get; set; }
public string SubmittedBy { get; set; }
public int SurveyId { get; set; }
public int QuestionId { get; set; }
public virtual Survey Survey { get; set; }
public virtual SurveyQuestion Question { get; set; }
public string Comment { get; set; }
}
public class SurveyAnswerValidator : AbstractValidator<SurveyAnswer>
{
public SurveyAnswerValidator()
{
//list your rules
RuleFor(x => x.SubmittedBy).Must(BeUnique).WithMessage("Already
submitted this survey");
}
private bool BeUnique(string submittedBy)
{
if(_context.SurveyAnswers.
FirstOrDefault(x => x.SubmittedBy == submittedBy) == null){
return true;
}
else{
return false;
}
}
}
If you want to check uniqueness in ViewModel you can use Remote.
public class SurveyAnswerVM{
[Key]
public int Id { get; set; }
public string Value { get; set; }
[Remote("HasSubmitted", "ControllerName")]
public string SubmittedBy { get; set; }
public int SurveyId { get; set; }
public int QuestionId { get; set; }
public virtual Survey Survey { get; set; }
public virtual SurveyQuestion Question { get; set; }
public string Comment { get; set; }
}
Where HasSubmitted is a method you may create in controller to return true if the user has submitted.
RemoteAttribute
https://msdn.microsoft.com/en-us/library/gg508808(VS.98).aspx
The best solution by vahdet (suggested in comments)
[Index("IX_AnswerQuestion", 2, IsUnique = true)]
[StringLength(36)]
public string SubmittedBy { get; set; }
public int SurveyId { get; set; }
[Index("IX_AnswerQuestion", 1, IsUnique = true)]
public int QuestionId { get; set; }

Xamarin.ios - Using NBuilder to build mocks throws TypeCreationException

I'm using the NBuilder library to build mock http responses, everything works fine in Android, but in iOS each time that I want to build a model class this exception is fired.
"FizzWare.NBuilder.TypeCreationException" and It says that my X model class doesn't have a parametless constructor, which actually has!. For example this model class:
public class Actor
{
public Actor() {
}
[JsonProperty("authorities")]
public List<Authority> Authorities { get; set; }
[JsonProperty("imageDerivatives")]
public ImageDerivatives ImageDerivatives { get; set; }
[JsonProperty("profileFileId")]
public PictureFile ProfilePicture { get; set; }
[JsonProperty("role")]
public Role Role { get; set; }
[JsonProperty("roleId")]
public int RoleId { get; set; }
[JsonProperty("status")]
public bool Status { get; set; }
[JsonProperty("updatedAt")]
public DateTime UpdatedAt { get; set; }
[JsonProperty("username")]
public string Username { get; set; }
[JsonProperty("createdAt")]
public DateTime CreatedAt { get; set; }
[JsonProperty("departmentId")]
public int DepartmentId { get; set; }
[JsonProperty("email")]
public string Email { get; set; }
[JsonProperty("firstName")]
public string FirstName { get; set; }
[JsonProperty("id")]
public int Id { get; set; }
[JsonProperty("isAppAdmin")]
public bool IsAppAdmin { get; set; }
[JsonProperty("lastName")]
public string LastName { get; set; }
[JsonProperty("password")]
public string Password { get; set; }
}
And this is how I build the mock response:
private Actor GetRandomActor()
{
return Builder<Actor>.CreateNew()
.With(a => a.FirstName = GetRandomFirstName())
.With(a => a.LastName = GetRandomLastName())
.With(a => a.ProfilePicture = GetRandomPictureFile())
.With(a => a.Email = GetRandomEmail())
.With(a => a.Username = GetRandomUserName())
.Build();
}
Try adding the Preserve attribute to your constructor so it does not get removed by the Linker:
[Preserve]
public Actor() {}
(Or add it at the class level [Preserve (AllMembers = true)])

How to include () in query

iam have two modal i I'm trying to include all Post that belong the User. However, I keep getting the following debug error:
Error 58 Cannot convert lambda expression to type 'string' because it is not a delegate type
please see pic
public IList<User> GetSliderImages()
{
var q = db.Users.Include(x=>x.Post).OrderByDescending(x => x.FPersonalUser).Where(x => x.typemanger == 1).ToList();
return q;
}
public class User
{
[Key]
public int ID_User { set; get; }
public Int16 ID_post { set; get; }
public bool Fbofd { set; get; }
public string FuserName { set; get; }
public bool Foffice { set; get; }
public byte[] FPicaddress { set; get; }
**public IList<Post> _post { set; get; }**
}
public partial class Post
{
[Key]
public int ID_Post { set; get; }
public string FNamePost { set; get; }
}
public virtual ICollection<Post> Post{ get; set; }
please use look like this for using relationship between two table then use include syntax.

MVC models converting error

How to set to a different model?
List<ORDER_DETAILSMetadata> result = db.ORDER_DETAILS.Where(p => p.Order_Number == id).ToList();
Error 6 Cannot implicitly convert type 'System.Collections.Generic.List<Mvc5.Models.ORDER_DETAILS>' to 'System.Collections.Generic.List<Mvc5.Models.ORDER_DETAILSMetadata>'
ORDER_DETAILSMetadata
MetadataType(typeof(ORDER_DETAILSMetadata))]
public partial class ORDER_DETAILS
{
// Note this class has nothing in it. It's just here to add the class-level attribute.
}
public class ORDER_DETAILSMetadata
{
public int Order_Details_ID { get; set; }
public Nullable<int> Order_Number { get; set; }
public Nullable<short> Sequence_Number { get; set; }
public string Item_Num { get; set; }
public Nullable<short> Order_Quantity { get; set; }
public Nullable<short> Ship_Quantity { get; set; }
}
ORDER_DETAILS.cs
public partial class ORDER_DETAILS
{
public int Order_Details_ID { get; set; }
public Nullable<int> Order_Number { get; set; }
public Nullable<short> Sequence_Number { get; set; }
public string Item_Num { get; set; }
public Nullable<short> Order_Quantity { get; set; }
public Nullable<short> Ship_Quantity { get; set; }
}
As far as i have understood, you can do something like this:
List<ORDER_DETAILSMetadata> result = db.ORDER_DETAILS.
Where(p => p.Order_Number == id).
Select(x => new ORDER_DETAILSMetadata
{
Order_Details_ID = x.Order_Details_ID,
Order_Number = x.Order_Number,
Sequence_Number = x.Sequence_Number,
Item_Num = x.Item_Num,
Order_Quantity = x.Order_Quantity,
Ship_Quantity = x.Ship_Quantity
}).ToList();
If you just want to convert one type of model to other type, you can do something like:
List<target> targetList = new List<target>(originalList.Cast<target>());
You can check the details about Cast() and OfType() here. Go for the first approach when you have different count and types of fields.

Getting Error: "A specified Include path is not valid. The EntityType Field' does not declare a navigation property"

Created method:
public List<Field> GetScheduleDetails()
{
var schedulefields = DBcontextFactory.Context.Set<Field>).Include("ScheduleField").ToList();
}
With the above method i am trying to fetch all joined(field.fieldid=schedulefield.fieldid) records from both tables. The field table is related with schedulefield table. Sorry if i am not familiar with technical terms.
Field Model:
public partial class Field : DOIEntity
{
public Field()
{
this.FilerResponses = new HashSet<FilerResponse>();
this.ScheduleFields = new HashSet<ScheduleField>();
}
public int FieldId { get; set; }
public string FieldDisplayName { get; set; }
public int FieldTypeId { get; set; }
public string HelpText { get; set; }
public Nullable<bool> OtherTextAllowed { get; set; }
public Nullable<int> ChoiceGroupId { get; set; }
public virtual FieldType FieldType { get; set; }
public virtual ICollection<FilerResponse> FilerResponses { get; set; }
public virtual ICollection<ScheduleField> ScheduleFields { get; set; }
}
ScheduleField Model:
public partial class ScheduleField
{
[Key]
public int ScheduleId { get; set; }
public int FieldId { get; set; }
public byte SortOrder { get; set; }
public Nullable<bool> IsMandatory { get; set; }
public Nullable<int> ParentFieldId { get; set; }
public Nullable<int> ParentChoiceId { get; set; }
public virtual Field Field { get; set; }
public virtual Schedule Schedule { get; set; }
}
When I call the method I am getting this error:
A specified Include path is not valid. The EntityType
'WorldBank.DOI.Data.Field' does not declare a navigation property with
the name 'ScheduleField'.
Why am I getting this error?
You have to use the property name of the Field class in the Include string:
public List<Field> GetScheduleDetails()
{
var schedulefields = DBcontextFactory.Context.Set<Field>).Include("ScheduleFields").ToList();
}
This will eager load the ScheduleField objects associated with the Field objects.
Note, you can also eager load many levels. For example, if you want to eager load the schedules of the ScheduleField object as well you would do this:
public List<Field> GetScheduleDetails()
{
var schedulefields = DBcontextFactory.Context.Set<Field>).Include("ScheduleFields.Schedule").ToList();
}

Resources