Create basic edition database in Azure with Entity Framework Code First - entity-framework

I'm trying to create a basic edition database in my Azure suscription using EF-Code First but I don't find the way to set the edition. Always database is created in standar edition.
I'm using DbContext.Database.CreateIfNotExists () method.

Unfortunately, EF relies on the default parameters when it creates a new database. You can choose to overwrite the default behavior by creating your own database initializer for EF.
public class BloggingContextCustomInitializer : IDatabaseInitializer<BloggingContext>
{
public void InitializeDatabase(BloggingContext context)
{
if (!context.Database.Exists())
{
SqlConnectionStringBuilder connstrBldr = new SqlConnectionStringBuilder(context.Database.Connection.ConnectionString);
connstrBldr.InitialCatalog = "master";
using (SqlConnection conn = new SqlConnection(connstrBldr.ConnectionString))
{
conn.Open();
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = "CREATE DATABASE [" + context.Database.Connection.Database + "] (EDITION = 'Basic')";
cmd.ExecuteNonQuery();
}
Database.SetInitializer(new CreateDatabaseIfNotExists<BloggingContext>());
context.Database.Initialize(force: true);
}
}
}

Related

PostgreSql - EFCore - Transaction not working as expected

The project is an ASP.Net core project using EF core en PostgreSql as database.
Basically the flow boils down to :
var transaction = Database.BeginTransaction();
var someEntityA = new EntityA()
{
Id = Guid.NewGuid().ToString();
};
await DataBase.DbSet<EntityA>.AddAsync(someEntityA);
await DataBase.SaveChangesAsync();
var someEntityB = new EntityB()
{
Id = Guid.NewGuid().ToString();
EntityAId = someEntityA.Id;
};
await DataBase.DbSet<EntityB>.AddAsync(someEntityB);
await DataBase.SaveChangesAsync();
transaction.Commit();
When the second SaveChangesAsync is hit, a FK violation is thrown.
Do we execute the same flow without
var transaction = Database.BeginTransaction();
transaction.Commit();
Then it is all fine.
This flow is spread over multiple classes (service and repository classes) so just removing the first SaveChangesAsync is not an option. Hence that is the reason why using the manually transaction handling.
This flow works fine in MS Sql but in PostgreSql apparantly not.
Any suggestions how to make it work in PostgreSql ?

How to connect sqlite db to unity

I have a preloaded db file, which is present in c drive in my system. If I connect that db file to unity project and try to get data from tables it didn't get any data and I am not getting any exceptions also. If I open this db file (which is present in c drive) with sqlite admin software it shows data in tables. Please suggest any idea, what I am missing. Here is the code I am using for connecting database to my unity project.
Public void OpenDatabase()
{
var dbfileName = "Testuser.db"
var _filePath = File.GetFullPath(dbfileName);
var _connectionString = "URI=file:" + _filePath;
dbcon = new SqliteConnection(_connectionString);
dbcon.Open();
}
When I am trying to create and read db file in the following manner working well.
Working code :
Public void OpenDatabase()
{
var _filePath = Application.PersistanceDataPath + "/" + "owndbfile.db";
if (!File.Exists(_filePath))
{
WWW loadDB = new WWW("jar:file://" + Application.PersistanceDataPath + "!/assets/" + "owndbfile.db");
while (!loadDB.isDone) { }
// then save to Application.persistentDataPath
File.WriteAllBytes(_filePath, loadDB.bytes);
}
var _connectionString = "URI=file:" + _filePath;
dbcon = new SqliteConnection(_connectionString);
dbcon.Open();
}
Please suggest any idea for reading data from tables, if db file is present in one of the drive in a system instead of a present in "application persistance" path.

mongo driver 2.7 missing eval function

I am trying to execute the random java scripts which work from mongo command line but I am trying to execute using mongo .net core c# driver I didn't find the eval function in new API, so I created the extension method like this....but it is not working as expected
public static async Task<BsonValue> EvalAsync(this IMongoDatabase database, string javascript)
{
var client = database.Client as MongoClient;
if (client == null)
throw new ArgumentException("Client is not a MongoClient");
var function = new BsonJavaScript(javascript);
var op = new EvalOperation(database.DatabaseNamespace, function, null);
using (var writeBinding = new WritableServerBinding(client.Cluster, new CoreSessionHandle(NoCoreSession.Instance)))
{
try
{
return await op.ExecuteAsync(writeBinding, CancellationToken.None);
}catch(Exception ex)
{
return await Task.FromResult<string>(ex.InnerException.StackTrace);
}
}
}
test script:
db.collection.updateOne(
{"PageId":NumberInt(12)},
{$set:
{
"PageName":"testpage",
"Section":[{
"SectionId":NumberInt(1),
"Title":"testpage",
"Contents":""}],
"Message":[{
"MessageId":NumberInt(1),
"MessageTypeId":NumberInt(2),
"MessageText":"teswt message."
}]
}
},
{upsert: true}
);
printjson(db.runCommand({getLastError:1}));
I am trying to execute the random java scripts which work from mongo command line but I am trying to execute using mongo .net core c# driver I didn't find the eval function in new API, so I created the extension method like this....but it is not working as expected

ServiceStack: How to deal with user registration

I'm trying to understand how to create a SignIn/SignUp service with ServiceStack and my database of choice is MongoDB:
public class AppHost : AppHostBase
{
public AppHost() : base("My Web Services", typeof(WelcomeService).Assembly) {}
public override void Configure(Container container)
{
Plugins.Add(new AuthFeature(() => new AuthUserSession(), new IAuthProvider[] {
new BasicAuthProvider()
}));
Plugins.Add(new RegistrationFeature());
var connectionString = ConfigurationManager.ConnectionStrings["mongodb"].ConnectionString;
var mongoClient = new MongoClient(connectionString);
var server = mongoClient.GetServer();
var db = server.GetDatabase("auth");
container.Register<ICacheClient>(new MemoryCacheClient());
container.Register<IUserAuthRepository>(new MongoDBAuthRepository(db, true));
}
The code above works correctly... it connects to the MongoDB server and creates the user table in the auth database. So far so good... What I'm trying to understand is how the built-in registration service works. If you look at my code, I enabled the RegistrationFeature but when I try to invoke it with http://localhost/register I always get a NotImplementedException. Does this mean I have to implement it from scratch? Is there any additional package to install? How do I actually invoke the default registration feature?

How to insert data to SQL Server DB using EF in MVC 2?

How do insert data to a SQl Server 2008 database server using Entity Framework from a user input on a web application.
I added a new EF connection o my model. I am able to see all the mappings correctly.
I currently have the following in my view:
m.PhoneNumber) %>
and in my controller
public ActionResult DialTone(Models.TelephoneModels telephone)
{
List<string> callType = new List<string>();
callType.Add("Standard");
callType.Add("Emergency");
ViewData["TypeOfCalls"] = new SelectList(callType);
if (!ModelState.IsValid)
{
return View("DialTone", telephone);
}
ViewData["Number"] = "You are currently connected to: " + telephone.PhoneNumber;
using (LogEntities db = new LogEntities())
{
var log = db.Logs.Single(m => m.PhoneNumber == telephone.PhoneNumber);
TryUpdateModel(log);
db.SaveChanges();
}
return View();
I want to log all phone numbers (or strings) that the user inputs in the TextBox - phonenNumber into the database.
I created a LOG database table with a column called "PhoneNumber". I cant seem to figure out how to insert the data into the table.
Any ideas?
Thanks!
:)
I figure it out. I used:
using (LogEntities db = new LogEntities())
{
Random random = new Random();
Log p = new Log();
p.ID = "400"; //Just a test
p.PhoneNumber = telephone.PhoneNumber;
db.AddToLogs(p);
db.SaveChanges();
}