Run Update Statement in Xamarin Studio - c#

I am using C# with xamarin studio. I can't find a working example to do an update statement against my db. I am trying to update a value of a record from 50 to 100.
This class represents one record in db:
[Table("record")]
public class Record
{
[PrimaryKey, AutoIncrementAttribute, Column("id")]
public int ID {get; set;}
[Column("value")]
public string Value {get; set;}
}
I can retrieve my records fine using:
string pathToDatabase = "mydb.db";
var db = new SqliteConnection (pathToDatabase);
myRecords = db.Query<Record>("SELECT * FROM records;");
The update should be as simple as doing Get and then Update.
var recToUpdate = db.Get<Record>(1); // record with primary key of 1.
recToUpdate.Value = "100"; // instead of 50
db.Update(recToUpdate);
It executes the update line fine, but the db still holds the older value of 50 instead of 100, when I run the app again.
Is my approach totally wrong?

If you are including an existing db in your app bundle, you cannot write to it. The app bundle is read only - this is an iOS security measure. In order to write to your db, you will need to move it to a user writable folder.
// in your app startup
string rootPath = "/mydb.db";
string userPath = Path.Combine(Environment.GetFolderPath (Environment.SpecialFolder.MyDocuments), "mydb.db";
// if userdb does not exist, copy it from the app bundle
if (!File.Exists(userPath)) {
File.Copy(rootPath, userPath);
}
When you want to actually access your db, you just use the db access code you already have, but be sure you are using the user writable path.
var db = new SqliteConnection (userPath);
Finally, if your db is read-only and will not be updated by the user, you can leave it in the app bundle and don't need to make a writable copy.

try with
recToUpdate.Value = "100"; // instead of 50
int i = db.Update(recToUpdate);
//check number of rows updated (i), db.Update() returns number of rows updated...
//or first try with recToUpdate.Value = 100; and see the number of rows affected + use try/catch if an error appears.

Related

Change DBase On Run Time C# app

I have developed an accounting program that is working beautifully, but now a new need has arisen.
When I enter the program, by default it reads the DB that I put in the file WinSCM.exe.config and if I want to change I have to exit the program and edit the file changing the DB name.
I did not want it to be this way, because my client does accounting for several companies and each company is a DB, so I wanted a way to select a company and when selecting this company the database is automatically changed in the release version.
I'm using Entity Framework to connect to Sql Server DB
Can someone help me?
I'm not sure what reading your DB is, but normally when you use Entity Framework you create a DbContext object whenever you need to do a query, or at utmost a few queries. You are not supposed to keep this DbContext alive for longer periods of time, say more than a few seconds. A minute would be very rare.
Whenever you create the Dbcontext instance you could use the default constructor that uses the config file to get the connection string to the database.
However one of the other constructors let you define the connection string to the database in the constructor. So if you want to construct your DbContext and connect it to a different database, just use that constructor
If you don't know the connection string, but you have a DbConnection to the database, there will be even a constructor for this case.
Hi Everybody Thank alot for your Answer. I just Solved My Question like this:
Fisrt of all, I created a class wich I called ConnetionTolls with this Content://.
public static class ConnectionTools
{
// all params are optional
public static void ChangeDatabase(
this DbContext source,
string initialCatalog = "",
string dataSource = "",
string userId = "",
string password = "",
bool integratedSecuity = true,
string configConnectionStringName = "")
/* this would be used if the
* connectionString name varied from
* the base EF class name */
{
try
{
// use the const name if it's not null, otherwise
// using the convention of connection string = EF contextname
// grab the type name and we're done
var configNameEf = string.IsNullOrEmpty(configConnectionStringName)
? source.GetType().Name
: configConnectionStringName;
// add a reference to System.Configuration
var entityCnxStringBuilder = new EntityConnectionStringBuilder
(System.Configuration.ConfigurationManager
.ConnectionStrings[configNameEf].ConnectionString);
// init the sqlbuilder with the full EF connectionstring cargo
var sqlCnxStringBuilder = new SqlConnectionStringBuilder
(entityCnxStringBuilder.ProviderConnectionString);
// only populate parameters with values if added
if (!string.IsNullOrEmpty(initialCatalog))
sqlCnxStringBuilder.InitialCatalog = initialCatalog;
if (!string.IsNullOrEmpty(dataSource))
sqlCnxStringBuilder.DataSource = dataSource;
if (!string.IsNullOrEmpty(userId))
sqlCnxStringBuilder.UserID = userId;
if (!string.IsNullOrEmpty(password))
sqlCnxStringBuilder.Password = password;
// set the integrated security status
sqlCnxStringBuilder.IntegratedSecurity = integratedSecuity;
// now flip the properties that were changed
source.Database.Connection.ConnectionString
= sqlCnxStringBuilder.ConnectionString;
}
catch (Exception ex)
{
// set log item if required
}
}
********the way to use it is like this***************
//I use this method in a diferent Class
//This method returns the Entity i use with new connections
public static MyEntities SelectDb(String DataBase,String sqlUser,String pw, String serverInstance){
var selectedDbase = new MyEntities();
// so only reference the changed properties
// using the object parameters by name
selectedDbase.ChangeDatabase
(
initialCatalog: DataBase,
userId: sqlUser,
password: pw,
dataSource: serverInstance// could be ip address 100.23.45.67 etc
);
return selectedDbase;
}
I want to thank everyone here and on other forums because this was the result of Your Contributions

Why are manual modifications made through SQL Server Object Explorer not shown but new records added are?

Hello I have a console application in which I hard codedly add records. Afterwards I make manual modifications and additions, showing them on the console aswell. The modifications and additions are seen on the console but the actual modification not, while the ones that were added are seen in their new state.
I.E.:
Record 1: "John" modified to "K"
Console application shows that Record 1 has been modified but the name property doesn't show the actual property it shows the old one.
While when I add Record 2 the console shows the actual data of the new record. Why is this?
Console.WriteLine("Welcome. Type YES to hard codedly add records.)");
if (Console.ReadLine().Equals("YES"))
{
using (var db = new HomeContext())
{
db.Homes.Add(new Home { Owner = "John", Time = DateTime.Now });
var count = db.SaveChanges();
DateTime old = db.Homes.Max(u => u.Time);
Console.WriteLine("{0} records saved to database", count);
Console.WriteLine("All records:");
foreach (var home in db.Homes)
{
Console.WriteLine(home);
}
Console.WriteLine("When you've made the manual changes through SQL Explorer GUI on Visual Studio, type YES");
if (Console.ReadLine().Equals("YES"))
{
var records = db.Homes.Where(u => u.Time > old).ToList();
Console.WriteLine("These are the recently made changes:");
foreach (var home in records)
{
Console.WriteLine(home);
}
}
Console.ReadKey();
}
}
CONSOLE OUTPUT:
ALL RECORDS:
Home 1 Owner John
adding modifying manually using Explorer
Typing YES
These are the recently made changes:
Home 1 Owner John
Home 2 Owner newRecord
Change the structure little bit.
While querying the database use new object of DB context

How can I read data from a table in Microsoft Azure Mobile Services and put it in my application?

I am using Xamarin Studio and Microsoft Azure Mobile Services. I am trying to read data I put into a table in Microsoft Azure Mobile Service and display it in my application. I followed all of the tutorials on the Azure website but I cant seem to find how to just get data from a table. I want to display to the User what they entered into the table.
Here is my code for entering data into the table:
//this just sets up the connection and table
private static readonly MobileServiceClient MobileService =
new MobileServiceClient (UsersConstants.ApplicationURL, UsersConstants.ApplicationKey);
private readonly IMobileServiceTable<UsersTable> usersTable = MobileService.GetTable<UsersTable>();
//this creates a new item
var NewItem = new UsersTable ();
NewItem.Name = NameTextBox.Text;
NewItem.Email = EmailTextBox.Text;
NewItem.Password = PasswordTextBox.Text;
//this inserts the item into the table I have set up
usersTable.InsertAsync(NewItem);
I then switch to another view in my application (its an iOS application) and I want to get this data from the table and put it in to my application. I have been looking around but I haven't found how to do it. Any help would be appreciated. Thanks!
You should be able to do something like this (exact syntax may need tweaking)
async private void GetUsers() {
var users = await usersTable.Where (u => u.Name == "Bob").ToListAsync();
}

Add an entity as LOG during property changing events of another entity

I am using linq to sql in a windows form application. there is a bug that I couldn't find the solution until now!
partial void OnAmountChanging(int? value)
{
OrderLog lg = new OrderLog()
{
Date = DateTime.Now,
IPAddress = System.Net.Dns.GetHostAddresses(Environment.MachineName)[0].ToString(),
NewData = value,
OldData = this.Amount,
Status = "Changed",
User = User.CurUser,
Order = this // each Order has one-to-many relation to OrderLog entity.
};
}
this is run as soon as the value of AMOUNT changes in datagridview.
after closing the form I try to save the created log to Database:
db.SubmitChanges();
then I face this error :
An attempt has been made to Attach or Add an entity that is not new, perhaps having been loaded from another DataContext. This is not supported
is there any solution?

Entity framework Context.SaveChanges not working at all

I'm having problems with this code. I´m able to connect to an mdf example database archive and generate the entity model. Althought I´m able to query the context model and retrieve information from the DB, when I try to update, delete or insert anything in the context and translate the changes to the DB Context.SaveChanges is not working. There is no Exception, the Entity model is updated properly, but the DB does not have the change.
Thanks in regard
public void addCourse(int courseId, int deptId, string courseTitle)
{
SchoolContexto = new SchoolEntities();
Course mycourse= new Course();
mycourse.CourseID = courseId;
mycourse.Credits = 10;
mycourse.DepartmentID = deptId;
mycourse.Title = courseTitle;
SchoolContexto.Courses.Add(mycourse);
SchoolContexto.SaveChanges();
SchoolContexto.Dispose();
}
Make property of .mdf file in your solution as
Copy to output Directory: "Copy only if newer"
Otherwise your db file will overwrite every time it runs
i suggest you to use this code :
public void addCourse(int courseId, int deptId, string courseTitle)
{
SchoolEntities entities = new SchoolEntities();
Course mycourse= new Course();
mycourse.CourseID = courseId;
mycourse.Credits = 10;
mycourse.DepartmentID = deptId;
mycourse.Title = courseTitle;
entities.Courses.Add(mycourse);
entities.SaveChanges();
}
if this is not working i suggest you to check your app.config file :)
Another way to add a new entity to the context is to change its state to Added. Have you tried this
using (var entities = new SchoolEntities())
{
Course mycourse= new Course();
mycourse.CourseID = courseId;
mycourse.Credits = 10;
mycourse.DepartmentID = deptId;
mycourse.Title = courseTitle;
context.Entry(mycourse).State = EntityState.Added;
entities.SaveChanges();
}
I think the Problem is that you working on localdb (.mdf) file .
I had the same problem but when i created new (sql server database connection)
Server name : (localdb)\MSSqlLocaldb .... it worked
A little off the subject but just in case you're here because you're performing an update and not an add, Check if you need a key on the table. I had a similar issue with EF Core. During an update on a table no error was generated but the SaveChanges returned 0. It wasn't until I tested adding a record, that it generated the key error. I resolved the key issue and the update went fine.
It happens because probably you don't have primary key in your Course entity.
I solved the problem by including the following namespace
using System.Data.SqlClient;

Categories