I’m trying to persist a very simple username/password combo in WP7 7.1 beta 2 using LINQ to SQL. So far everything works as expected (using the repository/model classes below)
I can create a new database, insert a record and query for that row (and it returns the persisted user no problem). But the next time I spin up the emulator the db context returns false when I exec this expression “db.DatabaseExists()”
Is this normal behavior for the emulator or am I not telling LINQ to persist this between sessions?
Thank you in advance
repository class
public class UserRepository : IDisposable
{
private readonly UserDataContext context;
public UserDataContext Context
{
get { return context; }
}
public UserRepository()
{
context = new UserDataContext(UserDataContext.DBConnectionString);
CreateDatabase();
}
private void CreateDatabase()
{
if (context.DatabaseExists() == false)
{
context.CreateDatabase();
}
}
public User GetByID(int id)
{
return context.GetTable<User>().FirstOrDefault(e => e.UserId.Equals(id));
}
public User GetByUsername(string username)
{
return context.GetTable<User>().FirstOrDefault(e => e.UserName.Equals(username));
}
public void Save(User user)
{
if (user.UserId > 0)
{
context.GetTable<User>().Attach(user, true);
}
else
{
context.GetTable<User>().InsertOnSubmit(user);
}
context.SubmitChanges();
}
public List<User> GetAll()
{
return context.GetTable<User>().ToList();
}
public int Count()
{
return context.GetTable<User>().Count();
}
public void Dispose()
{
if (context != null)
{
context.Dispose();
}
}
}
model
[Table]
public class User
{
[Column(IsPrimaryKey = true, IsDbGenerated = true, DbType = "INT NOT NULL Identity", CanBeNull = false, AutoSync = AutoSync.OnInsert)]
public int UserId { get; set; }
[Column]
public string UserName { get; set; }
[Column]
public string Password { get; set; }
}
context
public class UserDataContext : DataContext
{
public static string DBConnectionString = "Data Source=isostore:/User.sdf";
public UserDataContext(string connectionString) : base(connectionString) { }
public Table<User> Users;
}
This is expected behavior.
The database (and other data) is stored in Isolated Storage on the emulator. The emulator clears Isolated Storage on shutdown (see the first Note in MSDN here), so your database is deleted.