I am learning about Data Access Object Design Patterns and implementing it with c# / oracle. However when I try to run the program I get an error.
I am simply trying to add data to my database, however I keep getting the following error:
An unhandled exception of type 'System.StackOverflowException' occurred in Test.dll
It happens at my ReviewGame getter and setter.
Would you be so kind to view my code and see where I am going wrong? I would appreciate any help.
public string ReviewGame { get; set; }
"insert into review values(review_seq.nextval," + 2+ "," + review.MemberId + ", '" +review.ReviewGame+ "')";
ReviewDao reviewDao = new ReviewDaoImp();
Review r = new Review();
r.reviewGame = textBox1.Text;
r.ToString();
reviewDao.addReview(r);
}
Your properties call themselves in their getter and setter. You need to use a backing field to store the data:
private string _reviewGame;
public string ReviewGame
{
get { return _reviewGame; }
set { _reviewGame = value; }
}
Or you can use an auto property:
public string ReviewGame { get; set; }
(Note that I also changed to property name to start with an upper case, which is according to conventions.)
Related
I am getting an error when try to creation organization in the oracle webservice.
The field is set to nullable and I did not use that field. To resolve the issue I need to set HQBranchIndicator to empty string " ". But Other field error will occure there are too many fields to best. How to resolve this issue? Can i set all the fields to empty string?
[System.Xml.Serialization.XmlElementAttribute(IsNullable=true, Order=12)]
public string HQBranchIndicator {
get {
return this.hQBranchIndicatorField;
}
set {
this.hQBranchIndicatorField = value;
this.RaisePropertyChanged("HQBranchIndicator");
}
}
I looked all over Stack Overflow for this exception and found a lot of questions about it, but none that could solve my problem.
I am unit testing my application. All the tests were passing until I put an index on a column of one of my entities. I am using ABP, also.
It's worth noting that the app works fine when I run it, using SQL Server, but my unit tests use an in-memory database.
This works:
[Required]
public string Name
{
get { return PersonalInformation.Name; }
set { PersonalInformation.Name = value; }
}
This doesn't:
[Column(TypeName = "VARCHAR")]
[Index]
[Required]
public string Name
{
get { return PersonalInformation.Name; }
set { PersonalInformation.Name = value; }
}
The error "Sequence contains no elements" is thrown in a class I created that inherits from AbpIntegratedTestBase, in the first line of this method:
public void UsingDbContext(Action<UnitTestDbContext> action) {
using (var context = LocalIocManager.Resolve<UnitTestDbContext>())
{
action(context);
context.SaveChanges();
}
}
Can anyone help me with this? I'm trying to solve this for 3 days ^^"
I'm trying to use Azure Mobile Services to create a backend for an asynchronous multiplayer game. I'm using a sql database and a .NET backend on WAMS, calling the service from the .NET client (Xamarin.iOS specifically atm).
The class for the item being into the db:
public class Match {
public string Id { get; set; }
public int Challengers { get; set; }
string GameData { get; set; }
public List<string> Players { get; set; }
public string LastPlayer { get; set; }
public string Message { get; set; }
public string NextPlayer { get; set; }
public int PlayerGroup { get; set; }
}
I'm inserting it into the database using:
var matchtable = MobileService.GetTable <Match> ();
CurrentMatch = new Match {
Message = variant.ToString () + ", " + CurrentUser + " vs ??",
NextPlayer = CurrentUser,
Players = players,
PlayerGroup = playerGroup,
Challengers = 0,
Game = null,
LastPlayer = null
};
await matchtable.InsertAsync (CurrentMatch);
I'm then doing other things that will affect the match and need to update it again later, but I don't have an Id field for the CurrentMatch to be able to do the update. Everything I can find tells me that I should get the Id field back after the insert (either the method returning something or updating CurrentMatch itself with it), but it must all be talking about a javascript backend or different client or something. The InsertAsync method in the .NET client has no return value (well, technically returns Task) and the CurrentMatch doesn't get updated with the Id field from the call (also makes sense since it's not a ref or out parameter).
How on earth am I supposed to get the Id field for an object I just inserted into the database?
I'm assuming you are using the latest version of the Mobile Services client SDK, in which case you are calling this InsertAsync method here.
You're right that the parameter is not a ref or out parameter, but it can modify the fields of the object you passed in. In this case, it will modify the contents of the Match object.
My guess is that there is another code issue that's interfering. Or, if that code snippet is in a method, make sure it returns a Task and you await it before you check the contents of Id. A simple console log should help here.
If this doesn't solve the problem, then please include more context, otherwise the code you've written should behave as I've said.
I have a request like this:
ARequest : QueryBase<Person, Result>, IJoin<Person, OtherThing>
Person has the following field
[Ignore]
Public string Label { get { return FirstName + LastName; }
In my Result i have the following
public int Id;
public string Label
However, if i add an Ignore attribute to a field it gets ignored. So whenever i execute everything the only thing returned is a list of id's and in the QueryResponse the Label is always empty, if i however return a Person instead of Result i get a completely filled response.
So the question is, how do i make sure OrmLite does not search for label in the database, but sets the label in my custom return object.
After mythz explained to me the fact that if it doesn't map to your ormlite db it won't map to your resulting DTO later, i build a quick work around. Instead of returning my own response dto immediately in the following line:
ARequest : QueryBase<Person, Result>, IJoin<Person, OtherThing>
I just returned the person object:
ARequest : QueryBase<Person>, IJoin<Person, OtherThing>
Then in my service i wrote a simple mapper along the following lines:
QueryResponse<Result> response = result.ConvertTo<QueryResponse<Result>>();
response.Results = new List<Result>();
foreach (Person p in result.Results)
{
response.Results.Add(new Result{ Id = p.EmployeeId, Label = (p.FirstName + " " + p.LastName) });
}
return response
This way i made sure the label got filled with the firstname and the lastname, and yet did not have to redesign my result DTO so i could keep it very generic.
Not sure if I understand what you're trying to do, but if you're only looking to return Label you should be able to add it to the returned DTO, e.g:
public class Result
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Label { get { return FirstName + LastName } }
}
This question already has answers here:
Validation failed for one or more entities. See 'EntityValidationErrors' property for more details [duplicate]
(29 answers)
Closed 2 years ago.
My app gets the following error:
An exception of type
'System.Data.Entity.Validation.DbEntityValidationException' occurred
in EntityFramework.dll but was not handled in user code
Additional information: Validation failed for one or more entities.
See 'EntityValidationErrors' property for more details.
I get this error when trying to register a new user. Error happens on 'db.SaveChanges()'
Here is the code:
public ActionResult Registration(x.Models.User user)
{
if(ModelState.IsValid)
{
using(var db = new xDBEntities1())
{
var crypto = new SimpleCrypto.PBKDF2();
var encrpPass = crypto.Compute(user.password);
var sysUser = db.users.Create();
sysUser.email = user.email;
sysUser.username = user.username;
sysUser.password = encrpPass;
sysUser.premium_credits = 0;
sysUser.login_times = 0;
sysUser.last_ip = Request.ServerVariables["REMOTE_ADDR"];
sysUser.creation_ip = Request.ServerVariables["REMOTE_ADDR"];
sysUser.banned = 0;
sysUser.creation_date = DateTime.Now;
sysUser.creation_time = DateTime.Now.TimeOfDay;
db.users.Add(sysUser);
db.SaveChanges();
}
}
return RedirectToAction("Index", "Home");
}
edit:
User model class
public class User
{
[Required]
[StringLength(50)]
[Display(Name="Username: ")]
public String username { get; set; }
[Required]
[DataType(DataType.Password)]
[StringLength(50,MinimumLength=6)]
[Display(Name="Password: ")]
public string password { get; set; }
[Required]
[EmailAddress]
[StringLength(50)]
public string email { get; set; }
public int phonenumber { get; set; }
public int mobilephonenumber { get; set; }
}
}
How can I handle it ?
To solve this error, we can wrap the SaveChanges() method of DatabaseContext object in try block and in the Catch loop through each errors to find out where the error is. The code goes below.
try
{
db.SaveChanges();
}
catch (DbEntityValidationException ex)
{
foreach (var entityValidationErrors in ex.EntityValidationErrors)
{
foreach (var validationError in entityValidationErrors.ValidationErrors)
{
Response.Write("Property: " + validationError.PropertyName + " Error: " + validationError.ErrorMessage);
}
}
}
Once the error is found, you can work on that to fix it.
Hope this helps.
There is some sort of database validation happening preventing you from writing the data into it.
The solution is already stated on this page:
Validation failed for one or more entities. See 'EntityValidationErrors' property for more details
As an extra note to this as you are using .net mvc you should use System.Diagnostics.Debug.WriteLine() instead of Console.Writeline() and this will write to the debug output window when you are debugging. As you cannot write to the console when running a mvc project.
You can override the SaveChanges, to handle this exception and provide better exception details.
You can create a class "next" to your context class... the full code for that class is as follow:
using System.Data.Entity;
using System.Data.Entity.Validation;
using System.Linq;
namespace MyNamespace
{
public partial class MyContext : DbContext
{
// Override base SaveChanges to expand out validation errors so client gets an actually helpful message
public override int SaveChanges()
{
try
{
return base.SaveChanges();
}
catch (DbEntityValidationException ex)
{
// Retrieve the error messages as a list of strings.
var errorMessages = ex.EntityValidationErrors
.SelectMany(x => x.ValidationErrors)
.Select(x => x.ErrorMessage);
// Join the list to a single string.
var fullErrorMessage = string.Join("; ", errorMessages);
// Combine the original exception message with the new one.
var exceptionMessage = string.Concat(ex.Message, " The validation errors are: ", fullErrorMessage);
// Throw a new DbEntityValidationException with the improved exception message.
throw new DbEntityValidationException(exceptionMessage, ex.EntityValidationErrors);
}
}
}
}
Check this for more information: http://devillers.nl/blog/improving-dbentityvalidationexception/
Even though there is an accepted answer already, my experience could probably help someone in the future. For a quick test you can check the data which you are inputting to the database in Configuration.cs file and then in Model you can check the validation conditions. For example, in my case I would put following validation condition in a model:
[Range(1, 100),DataType(DataType.Currency)]
public decimal Price { get; set; }
And then, inside the Configuration.cs assigning the price to be:
new Photo{
Title = "Photo 2",
DateTaken = DateTime.Parse("2013-6-15"),
Genre = "Nature",
CameraModel = "Canon",
Price = 200
}
This, created EntityFrameworkExceptions and prevented database from seeding.
The password Length in the DB and the Model must be >= that the length of encrpPass.
Check the size of the database fields that you are trying to save data to. Changing a field from varchar(50) to varchar(max) did the trick for me.
If you are using Entity Framework you might have to delete and add the table that you made changes to.
Maybe this is helpful for someone :
This error occurred because I changed the field properties in EF SQL Server DB from var(100) to var(200). I updated properly in the DB, but forgot to update the ADO properties. In the .edmx file you can click on the columnname and change the properties, after that it worked for me.