I want use a database in my app, but there are some errors:
An exception of type 'System.Data.SqlServerCe.SqlCeException' occurred in Microsoft.Phone.Data.Internal.ni.dll but was not handled in user code
If there is a handler for this exception, the program may be safely
continued.
It occurs on this:
if (true == db.PersonData.Any())
and
db.PersonData.InsertOnSubmit(newData);
The code worked on wp7....how do you fix it?
Thx~
[Table]
public class CPersonData
{
[Column]
public string Lat { get; set; }
[Column]
public string Lon { get; set; }
[Column]
public string SelectShopType { get; set; }
[Column]
public DateTime UpdateTime { get; set; }
}
public class DataBase : DataContext
{
public Table<CPersonData> PersonData;
public DataBase(string strConnection) : base(strConnection)
{
if (false == this.DatabaseExists())
this.CreateDatabase();
}
}
using (var db = new DataBase("Data Source=isostore:/FindTea.sdf"))
{
CPersonData newData = new CPersonData();
newData.Lat = "";
newData.Lon = "";
newData.SelectShopType = "1,2,3";
db.PersonData.InsertOnSubmit(newData);
db.SubmitChanges();
}
I found the problem!!!I didn't put a primary key in this table, so when I add this
[Column(IsPrimaryKey = true, IsDbGenerated = true, DbType = "INT NOT NULL Identity", AutoSync = AutoSync.OnInsert, CanBeNull = false)]
public int ID { get; set; }
The App doesn't crash!!!!
Related
I have a simple table which I can perform Inser and Read operations using MySQL Commands.
For some reason, when using Linq2DB I get the following ERROR:
Connection option 'datasource' is duplicated.
at MySql.Data.MySqlClient.MySqlBaseConnectionStringBuilder.AnalyzeConnectionString
This Works:
private void BulkInsert(List<string> rows)
{
var commandText = new StringBuilder("INSERT INTO cloudevents (JobId, Name, ErrorUrgency, EventCategory, EventType, Time, Parameters) VALUES ");
commandText.Append(string.Join(",", rows));
commandText.Append(";");
try
{
using (MySqlCommand command = MySqlConnectionConnector.CreateCommand())
{
command.CommandText = commandText.ToString();
command.CommandType = CommandType.Text;
command.ExecuteNonQuery();
}
}
catch (Exception e)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(e);
throw;
}
finally
{
rows.Clear();
}
}
This Throw Error:
using (var db = new EocIpcDB())
{
db.Insert(new EventsOnCloudData()
{
JobId = 2000,
ErrorUrgency = "Error",
EventCategory = "HW",
EventType = "Disk",
Name = "Haedware Events",
Time = DateTime.Now,
Parameters = "Lots of Parameters"
});
var query = from p in db.EventsOnCloudData select p;
return query.ToList();
}
My Data Table:
[Table("cloudevents")]
public class EventsOnCloudData
{
[PrimaryKey, Identity]
public int Key { get; set; } // primary key / uid
[Column(Name = "Name"), NotNull]
public string Name { get; set; }
[Column(Name = "ErrorUrgency"), NotNull]
public string ErrorUrgency { get; set; }
[Column(Name = "EventCategory"), NotNull]
public string EventCategory { get; set; }
[Column(Name = "EventType"), NotNull]
public string EventType { get; set; }
[Column(Name = "JobId"), NotNull]
public int JobId { get; set; }
[Column(Name = "Time"), NotNull]
public DateTime Time { get; set; } //UTC
[Column(Name = "Parameters"), NotNull]
public string Parameters { get; set; } //JSON Parameters
}
LinqtoDB Data Connection Class:
public class EocIpcDB : LinqToDB.Data.DataConnection
{
public EocIpcDB() : base("eocipcdb") { }
public ITable<EventsOnCloudData> EventsOnCloudData => GetTable<EventsOnCloudData>();
}
Linq 2 DB settings Class:
public class EventsOnCloudSettings : ILinqToDBSettings
{
public IEnumerable<IDataProviderSettings> DataProviders => Enumerable.Empty<IDataProviderSettings>();
public string DefaultConfiguration => "SqlServer";
public string DefaultDataProvider => "SqlServer";
public IEnumerable<IConnectionStringSettings> ConnectionStrings
{
get
{
yield return
new ConnectionStringSettings
{
Name = "eocipcdb",
ProviderName = ProviderName.MySql,
ConnectionString = #"Server=.\;datasource=localhost;port=3306;database=eocipcdb;username=root;password=HPdfeHPdfe#1;"
};
}
}
}
internal class ConnectionStringSettings : IConnectionStringSettings
{
public string Name { get; set; }
public string ProviderName { get; set; }
public string ConnectionString { get; set; }
public bool IsGlobal => false;
}
This error generated by MySql.Data provider itself because you have server option set twice: Server=.\;datasource=localhost;. Server and Data Source are synonyms, alongside with host, data source, address, addr and network address
I have a custom class of the following type
[Table]
class MyApp
{
public MyApp()
: base()
{
}
[Column(IsPrimaryKey=true, UpdateCheck = UpdateCheck.Never)]
public string appCode { get; set; }
[Column(UpdateCheck = UpdateCheck.Never)]
public string procCode { get; set; }
}
I have another class which contains a list of MyApp objects which is as below:
[Table]
class ApplicationUser
{
public ApplicationUser()
:base()
{
}
[Column(IsPrimaryKey = true, UpdateCheck = UpdateCheck.Never)]
public string userId { get; set; }
[Column(UpdateCheck = UpdateCheck.Never)]
public List<MyApp> applicationList { get; set; }
}
While calling the CreateDatabase() method in my DataContext class i get the following error:
Unable to determine SQL type for 'System.Collections.Generic.List`1[XCell.Framework.data.MyApp]'
Please guide me on this.
As I see the problem is that the applicationList is marked with the Column attribute, though it represents a relation.
Basically you will have to correctly map the relation between those entities using EntityRef<T> and EntitySet<T> classes and the Association attribute.
This article may be helpful.
The example with the corrected mapping (for one-to-many relation) below:
Adjusted ApplicationUser class
[Table]
public class ApplicationUser
{
private EntitySet<MyApp> _userApplications = new EntitySet<MyApp>();
[Column(IsPrimaryKey = true, UpdateCheck = UpdateCheck.Never)]
public string UserId { get; set; }
[Association(Storage = "_userApplications", ThisKey = "UserId", OtherKey = "ApplicationUserId")]
public EntitySet<MyApp> ApplicationList
{
get { return _userApplications; }
set { _userApplications = value; }
}
}
And the adjusted MyApp class
[Table]
public class MyApp
{
private EntityRef<ApplicationUser> _applicationUserRef;
[Column(IsPrimaryKey = true, UpdateCheck = UpdateCheck.Never)]
public string AppCode { get; set; }
[Column(UpdateCheck = UpdateCheck.Never)]
public string ProcCode { get; set; }
[Column]
public string ApplicationUserId { get; set; }
[Association(Name = "FK_MyApp_ApplicationUser", Storage = "_applicationUserRef", ThisKey = "ApplicationUserId", OtherKey = "UserId")]
public ApplicationUser ApplicationUserReference
{
get { return _applicationUserRef.Entity; }
set { _applicationUserRef.Entity = value; }
}
}
Saving the change to a temp variable is successful as when debugging I can see the values changing, however when I actually try to save the changes to the database, the required field is not being changed.
I am trying to change the value of the field from 'Being Investigated' to 'Closed'
nemesysEntities db2 = new nemesysEntities();
report report = db2.reports.Find(investigation.report_id);
report_status rep = db2.report_status.Find(3);
report.report_status = rep;
report.report_status.description = "Closed";
report.report_status.id = 3;
db2.Entry(report).State= EntityState.Modified;
db2.SaveChanges();
The table that stores the reports is called reports, and investigation.report_id represents the id of the report being investigated. Hence by passing the report id as a value, the table should find the report in the reports table and change the value of the action status to Closed, by the below line of code, (the id of the action "closed" in the database is 3)
report_status rep = db2.report_status.Find(3);
However the required changes in the database are not being stored.
Any ideas??
This is the model of the report
namespace WebApplication2.Models
{
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Data.Entity;
using System.Data.Entity.Validation;
using System.Diagnostics;
using System.Web;
public partial class report
{
public report()
{
this.investigations = new HashSet<investigation>();
HttpCookie _userId = System.Web.HttpContext.Current.Request.Cookies["User"];
string userId="";
nemesysEntities db = new nemesysEntities();
if(_userId!=null)
{
this.user_id = Convert.ToInt32(_userId["Id"]);
user temp=db.users.Find(user_id);
this.email = temp.email;
this.phone = temp.phone;
temp.ConfirmPassword = temp.password;
int i = temp.points;
i++;
temp.points = i;
db.Entry(temp).State = EntityState.Modified;
try
{
db.SaveChanges();
}
catch (DbEntityValidationException dbEx)
{
foreach (var validationErrors in dbEx.EntityValidationErrors)
{
foreach (var validationError in validationErrors.ValidationErrors)
{
Trace.TraceInformation("Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage);
}
}
}
}
else
{
this.user_id = 13;
}
this.status_id = 1;
}
public int id { get; set; }
[Display(Name = "Date of near miss")]
public System.DateTime date { get; set; }
[Display(Name = "Location")]
public string location { get; set; }
[DisplayName("Type")]
public int type_id { get; set; }
[Display(Name = "Description")]
public string description { get; set; }
public int status_id { get; set; }
public int user_id { get; set; }
[Display(Name = "Email Address")]
public string email { get; set; }
[Display(Name = "Phone Number")]
public string phone { get; set; }
public int votes { get; set; }
public virtual ICollection<investigation> investigations { get; set; }
public virtual report_status report_status { get; set; }
public virtual report_type report_type { get; set; }
public virtual user user { get; set; }
}
}
This is the model of the investigator. You can see that in one of the setters I am using the same method I am attempting to use to change the status of the report.
namespace WebApplication2.Models
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Data.Entity;
using System.Data.Entity.Validation;
using System.Diagnostics;
using System.Web;
public partial class investigation
{
public investigation()
{
HttpCookie _userId = System.Web.HttpContext.Current.Request.Cookies["User"];
if (_userId != null)
{
this.investigator_id = Convert.ToInt32(_userId["Id"]);
//5 is the primary key of "Being investigated" in type of action
this.action_id = 5;
this.cause = "";
this.date_of_action = new DateTime(2012, 1, 3);
}
}
public int id { get; set; }
[Display (Name="Formal Description")]
public string formal_description { get; set; }
[Display(Name = "Cause of Hazard")]
public string cause { get; set; }
[Display(Name = "Action Take")]
public int action_id { get; set; }
[Display(Name = "Date of Action")]
public System.DateTime date_of_action { get; set; }
public int investigator_id { get; set; }
int _report_id;
[Display(Name = "Report Id:")]
public int report_id
{
get
{
return _report_id;
}
set
{
_report_id = value;
nemesysEntities db = new nemesysEntities();
report report = db.reports.Find(this.report_id);
//2 is the primary key of "Being investigated" in report status
report_status rep = db.report_status.Find(2);
report.report_status = rep;
db.Entry(report).State = EntityState.Modified;
try
{
db.SaveChanges();
}
catch (DbEntityValidationException dbEx)
{
foreach (var validationErrors in dbEx.EntityValidationErrors)
{
foreach (var validationError in validationErrors.ValidationErrors)
{
Trace.TraceInformation("Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage);
}
}
}
}
}
public virtual investigation_action investigation_action { get; set; }
public virtual report report { get; set; }
public virtual user user { get; set; }
}
}
Here's my DataContext class:
public class Dealer : DataContext
{
public Table<Vehicle> Vehicles;
public Table<Customer> Customers => GetTable<Customer>();
public Table<Account> Accounts;
public Table<Transaction> Transactions;
public Dealer(string connection) : base(connection) { }
}
Here's the Customer Class:
[Table(Name="Customers")]
public class Customer
{
[Column(IsPrimaryKey = true, DbType = "int NOT NULL IDENTITY", IsDbGenerated = true, CanBeNull = false)]
public int CustomerID { get; set; }
[Column(CanBeNull = false)]
public string FirstName { get; set; }
[Column(CanBeNull = false)]
public string LastName { get; set; }
[Column(CanBeNull = false)]
public string SSN { get; set; }
public override string ToString()
{
return string.Concat(this.FirstName, " ", this.LastName, " ", this.SSN);
}
private EntitySet<Vehicle> vehicles = null;
[Association(Storage = "vehicles", OtherKey = "CustomerID", ThisKey = "CustomerID")]
public EntitySet<Vehicle> Vehicles { get; set; }
//implement INotifyPropertyChanged
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
Here's the code that throws the NullReferenceException:
private void Button_Click(object sender, RoutedEventArgs e)
{
Customer c = new Customer() { FirstName="John", LastName="Smith", SSN = "123456" };
Dealer d = new Dealer(App.connectionString);
d.Customers.InsertOnSubmit(c); //d.Customers is null and throws null reference exception.!!!
try
{
d.SubmitChanges();
}
catch (Exception x)
{
MessageBox.Show(x.Message);
}
I have googled for many hours now and I can't figure out why it's throwing NullReferenceException... (found a lot of other posts but non of the solutions seem to work for me )
Please help ...
Thanks in advance.
I had the same problem yesterday. Removing getters and setters from DataContext class helped. By the way I'd change CustomerId column property by addingAutoSync=Autosync.OnInsert
I am trying to put some distributed caching into play, I'm using this indeXus.Net Shared Cache .
It Requires that the object being cached is serializable, which it is here is the class object.
[Serializable]
public class Members
{
public Members()
{}
public Members(string aspnetusername, string aspnetpassword,
string emailaddr,string location)
: this(0,0,aspnetusername, aspnetpassword,emailaddr,DateTime.Now, location,
0,0,DateTime.Now,DateTime.Now,DateTime.Now,false)
{ }
public Members(Int64? row,int memberid, string aspnetusername, string aspnetpassword,
string emailaddr,DateTime datecreated, string location, int daimokugoal, int previewimageid,
DateTime lastdaimoku, DateTime lastnotifed, DateTime lastactivitydate, bool isactivated)
{
this.Row = row;
this.MemberID = memberid;
this.Aspnetusername = aspnetusername;
this.Aspnetpassword = aspnetpassword;
this.EmailAddr = emailaddr;
this.DateCreated = datecreated;
this.Location = location;
this.DaimokuGoal = daimokugoal;
this.PreviewImageID = previewimageid;
this.LastDaimoku = lastdaimoku;
this.LastNotefied = lastnotifed;
this.LastActivityDate = lastactivitydate;
this.IsActivated = this.IsActivated;
this.Details = new LazyList<MemberDetails>();
this.Blogs = new LazyList<MemberBlogs>();
this.Daimoku = new LazyList<MemberDaimoku>();
this.Determinations = new LazyList<MemberDeterminations>();
this.Encouragements = new LazyList<MemberEncouragements>();
this.Entries = new LazyList<MemberEntries>();
this.Friends = new LazyList<MemberFriends>();
this.Stats = new LazyList<MemberStats>();
}
public Int64? Row { get; set; }
public int MemberID { get; set; }
public string Aspnetusername { get; set; }
public string Aspnetpassword { get; set; }
public string EmailAddr { get; set; }
public DateTime DateCreated { get; set; }
public string Location { get; set; }
public int DaimokuGoal { get; set; }
public int PreviewImageID { get; set; }
public DateTime LastDaimoku { get; set; }
public DateTime LastNotefied { get; set; }
public DateTime LastActivityDate { get; set; }
public bool IsActivated { get; set; }
public LazyList<MemberDetails> Details { get; set; }
public LazyList<MemberBlogs> Blogs { get; set; }
public LazyList<MemberDaimoku> Daimoku { get; set; }
public LazyList<MemberDeterminations> Determinations { get; set; }
public LazyList<MemberEncouragements> Encouragements { get; set; }
public LazyList<MemberEntries> Entries { get; set; }
public LazyList<MemberFriends> Friends { get; set; }
public LazyList<MemberStats> Stats { get; set; }
}
The LINQtoSql is this that populates this class.
public IQueryable<Members> GetMemberInfo()
{
using (var t = new TransactionScope(TransactionScopeOption.Required,
new TransactionOptions { IsolationLevel = System.Transactions.IsolationLevel.ReadUncommitted }))
{
var results = from m in _datacontext.ViewMembers
let details = GetMemberDetails(m.MemberID)
let determinations = GetMemberDeterminations(m.MemberID)
let daimoku = GetMemberDaimoku(m.MemberID)
let entries = GetMemberEntries(m.MemberID)
let blogs = GetMemberBlogs(m.MemberID)
let encouragements = GetMemberEncouragements(m.MemberID)
let friends = GetMemberFriends(m.MemberID)
let points = GetMemberStats(m.MemberID)
select new Members
{
Row = m.Row,
MemberID = m.MemberID,
Aspnetusername = m.Aspnetusername,
Aspnetpassword = m.Aspnetpassword,
EmailAddr = m.EmailAddr,
DateCreated = m.DateCreated,
Location = m.Location,
DaimokuGoal = m.DaimokuGoal,
PreviewImageID = m.PreviewImageID,
LastDaimoku = m.LastDaimoku.Value,
LastNotefied = m.LastNotefied.Value,
LastActivityDate = m.LastActivityDate.Value,
IsActivated = m.IsActivated,
Details = new LazyList<MemberDetails>(details),
Determinations = new LazyList<MemberDeterminations>(determinations),
Daimoku = new LazyList<MemberDaimoku>(daimoku),
Entries = new LazyList<MemberEntries>(entries),
Blogs = new LazyList<MemberBlogs>(blogs),
Encouragements = new LazyList<MemberEncouragements>(encouragements),
Friends = new LazyList<MemberFriends>(friends),
Stats = new LazyList<MemberStats>(points)
};
return results;
}
}
But for some reason I am getting this error
System.Runtime.Serialization.SerializationException: Type 'System.Data.Linq.DataQuery`1[[DaimokuBeta.MVC.Data.MemberDetails, DaimokuBeta.MVC.Data, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]' in Assembly 'System.Data.Linq, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' is not marked as serializable.
MemberDetails is serializable too..so not sure why it thinks it can't be serialized
Any ideas?
I believe that it's your LazyList implementation that cannot be serialized because the exception is telling us that the generic type DataQuery (from assembly System.Data.Linq) is not serializable. Is this type connected to your LazyList in any way?
If you are trying to cache the Members DTO (data transfer object) it's probably not a good idea to be applying lazy loading because it may only be executed in a very unpredictable moment.
Cache should usually be applied to data that has already been loaded/computed. Otherwise there may not be much point in using cache.