Create database using code first Entity Framework in SQL Server - entity-framework-6

I am using code first EF and new to this framework. I am trying to create a database using Database.SetInitializer but it looks like I need SQL Server Express. But I have to create database in SQL Server 2014. How to do this?
Can anybody explain this with the example from EF-dbcontext book which has following classes.
public class BreakAwayContext : DbContext
{
public DbSet<Destination> Destinations { get; set; }
public DbSet<Lodging> Lodgings { get; set; }
public DbSet<Trip> Trips { get; set; }
public DbSet<Person> People { get; set; }
public DbSet<Reservation> Reservations { get; set; }
public DbSet<Payment> Payments { get; set; }
public DbSet<Activity> Activities { get; set; }
}
class Program
{
static void Main(string[] args)
{
Database.SetInitializer(new InitializeBagaDatabaseWithSeedData());
try
{
using (var context = new BreakAwayContext())
{
foreach (var destination in context.Destinations)
Console.WriteLine(destination.Name);
}
}
catch(Exception ex){
Console.WriteLine(ex.ToString());
}
Console.Read();
}
}
public class InitializeBagaDatabaseWithSeedData : DropCreateDatabaseAlways<BreakAwayContext>
{
protected override void Seed(BreakAwayContext context)
{
context.Destinations.Add(new Destination
{
Name = "Hawaii",
Country = "USA",
Description = "Sunshine, beaches and fun."
});
context.Destinations.Add(new Destination
{
Name = "Wine Glass Bay",
Country = "Australia",
Description = "Picturesque sandy beaches."
});
}

Set your connection string in your constructor:
public class BreakAwayContext : DbContext
{
public BreakAwayContext()
: base("MyConnectionString", throwIfV1Schema: false)
{
}
...
Then set your connection string in web.config or app.config:
<connectionStrings>
<add name="MyConnectionString" connectionString="Data Source=servername;Initial Catalog=dbname;..." providerName="System.Data.SqlClient" />
</connectionStrings>

Related

Neo4jClient - Query did not return the the values in view

I installed neo4j and neo4jClient in my MVC Project 4.0.
Install example movie database from the guide
:play movies
I made the following settings in Web.Config:
<appSettings>
<add key="ClientDBUrl" value="http://localhost:7474/db/data" />
<add key="ClientDBUser" value="neo4j" />
<add key="ClientDBPassword" value="password" />
</appSettings>
Made WbApiConfig.cs in App_Start Folder
public class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.MapHttpAttributeRoutes();
config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
config.Formatters.JsonFormatter.SerializerSettings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore;
var appXmlType = config.Formatters.XmlFormatter.SupportedMediaTypes.FirstOrDefault(t => t.MediaType == "application/xml");
config.Formatters.XmlFormatter.SupportedMediaTypes.Remove(appXmlType);
//Use an IoC container and register as a Singleton
var url = ConfigurationManager.AppSettings["ClientDBUrl"];
var user = ConfigurationManager.AppSettings["ClientDBUser"];
var password = ConfigurationManager.AppSettings["ClientDBPassword"];
var client = new GraphClient(new Uri(url), user, password);
client.Connect();
GraphClient = client;
}
public static IGraphClient GraphClient { get; private set; }
}
Created a Model
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
}
Then i write simple query in controller to exact the data in view
public ActionResult Index()
{
var query = WebApiConfig.GraphClient.Cypher.Match("(p:Person)-[:ACTED_IN]->(m:Movie {title: 'Top Gun'})")
.Return(p => p.As<Person>()).Results;
return View(query.ToList());
}
and in view
#model IEnumerable<Neo4j_TestProject1.Models.Person>
<table>
#foreach (var item in Model) {
<tr>
<td>
#item.Name
</td>
</tr>
}
</table>
But i get the error of "Object Reference not Set to an Instance" in my query.
I can't reproduce the error - but! - I think I know where it's going wrong for you.
The Movies data set does have a Person label, but if you look at it, you'll see there are only 2 properties born and name. So you're Age and Id properties will never be set, ignoring that for the moment as you aren't viewing them - the Name property you have will also not be set - and that's because Neo4j is case-sensitive.
If you change your Person class to:
public class Person
{
public int Id { get; set; }
[JsonProperty("name")] // <-- Added
public string Name { get; set; }
public int Age { get; set; }
}
You will get names, you're basically telling Neo4jClient to translate for you.
You could modify your Person class to be like this:
public class Person
{
private int _born;
public int Id { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("born")]
public int Born
{
get => _born;
set
{
_born = value;
Age = DateTime.Now.Date.Year - value;
}
}
public int Age { get; set; }
}
Which would get you the age if you want it!

MVC Code First Approach doesn't seed data for the Tables. Do we require to enable migration?

Table to be Created using the below class..
public class Country
{
[Key]
public int CountryId { get; set; }
[Display(Name = "Country Name")]
[Required]
public string CountryName { get; set; }
[Display(Name = "Country Code")]
[Required]
public string CountryCode { get; set; }
}
DBContext Class Inherited
public class DatabaseContext:DbContext
{
public DatabaseContext() : base("StudentContext")
{
Database.SetInitializer(new DatabaseRepository());
}
public DbSet<Country> Countrys { get; set; }
}
Web.Config Conneection String
<add name="StudentContext" connectionString="Server=XXXXXX; Database=StudentDB; User Id=xxxxxxx; password=xxxxxxx" providerName="System.Data.SqlClient" />
Class for Overriding the Seed Method
public class DatabaseRepository :DropCreateDatabaseIfModelChanges<DatabaseContext>
{
protected override void Seed(DatabaseContext context)
{
Country _country = new Country();
_country.CountryName = "India";
_country.CountryCode = "IN";
context.Countrys.Add(_country);
context.SaveChanges();
base.Seed(context);
}
}
Using MVC Web Application I am trying to List the Country List.
The code is able to create the Database and the table using this approach but the seed method is not being executed.
I did try to go through some of the video available and make changes accordingly but nothing seems to execute the Seed Method.
You also need this attribute:
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
like:
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int CountryId { get; set; }
to auto generate the columns. See this for an explanation.
just Try to set AutomaticMigrationsEnabled to true in your configuration file constructor , like below example
My Working code:
internal sealed class Configuration : DbMigrationsConfiguration<ApplicationDbContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = true;
}
protected override void Seed(ApplicationDbContext context)
{
}
}
Note: the above code as ran the seed automatically and put the data into the database
In your case:
public class DatabaseRepository :DbMigrationsConfiguration<DatabaseContext >
{
public DatabaseRepository()
{
AutomaticMigrationsEnabled = true;
}
protected override void Seed(DatabaseContext context)
{
Country _country = new Country();
_country.CountryName = "India";
_country.CountryCode = "IN";
context.Countrys.Add(_country);
context.SaveChanges();
base.Seed(context);
}
}
And see its works, kindly let me know your thoughts or feedbacks
Thanks
Karthik

ORA-01918: user 'dbo' does not exist

I am trying to connect oracle with MVC as below
Config file
<connectionStrings>
<add name="OracleDbContext" providerName="Oracle.ManagedDataAccess.Client" connectionString="User Id=test;Password=123_test;Data Source=local:xxxx/liveprod" />
</connectionStrings>
User table model
public class sys_users
{
[Key]
public long us_id { get; set; }
public string us_name { get; set; }
public string us_pass { get; set; }
}
Db context
public class OracleDBContext : DbContext
{
public OracleDBContext()
: base("name=OracleDbContext")
{
}
public virtual DbSet<sys_users> sys_users { get; set; }
}
Controller
public ActionResult Login(string Name, string Password)
{
var u = db.sys_users.Where(d => d.us_name.Equals(Name) && d.us_pass.Trim().Equals(Password)).FirstOrDefault();
if (u != null)
{
Session["LoggedInAdminUserId"] = u.us_id.ToString();
Session["LoggedInAdminUsername"] = u.us_name.ToString();
return RedirectToAction("Login");
}
else
{
ViewBag.message = "Username or Password is invalid.";
}
return View();
}
But at the line
var u = db.sys_users.Where(d => d.us_name.Equals(Name) && d.us_pass.Trim().Equals(Password)).FirstOrDefault();
I am getting error
ORA-01918: user 'dbo' does not exist
Do I need to do anything else for using oracle tables as model in MVC??
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
//Configure default schema
modelBuilder.HasDefaultSchema("STORE");
}
Entity default schema user is based on Sql (dbo) change the default to anything else but in UPPERCASE

why wont my asp.net mvc application seed work properly?

I have the following code to create entities and seed them with data for use in an asp.net mvc application. I am using code first and entity framework. I generate controllers and run the application but on the index.cshtml page my list is empty where the seed data should be.
public class MyContext : DbContext
{
public MyContext() : base("dataDb") {}
public DbSet<Owner> Owners { get; set; }
public DbSet<Pet> Pets { get; set; }
}
public class MyInitializer : DropCreateDatabaseAlways<MyContext>
{
protected override void Seed(MyContext context)
{
// seed database here
context.Owners.AddOrUpdate(
new Owner()
{
//name=,
//id=,
Pets = new List<Pet> { new Pet()
{
//id=,
//name=,
},
new Pet()
{
//id=,
//name=,
}}
},
new Owner()
{
//id=,
//name=,
Pets = new List<Pet> { new Pet()
{
//id=,
//name=,,
}
}
}
);
context.SaveChanges();
}
}
public class Owner
{
public int OwnerId { get; set; }
public string Name { get; set; }
public virtual List<Pet> Pets { get; set; }
}
public class Pet
{
public int PetId { get; set; }
public string Name { get; set; }
public string Type { get; set; }
public virtual Owner Owner { get; set; }
}
}
I found a solution to this problem:
Database.SetInitializer(new MyInitializer()); //important for seed to work
add this line to the context constuctor:
public MyContext() : base("dataDb") {}
You can also add it to your web.config. When it comes to deployment, you can easily remove it from the web.config by using configuration transformer.
<entityFramework>
<contexts>
<context type="MyProject.MyContext, MyProject">
<databaseInitializer type="MyProject.MyInitializer, MyProject" />
</context>
</contexts>
...
</entityFramework>
<connectionStrings>
<add name="MyContext" connectionString="Data Source=(LocalDb)\MSSQLLocalDB;Initial Catalog=OwnersPets; AttachDBFilename=|DataDirectory|\OwnersPets.mdf; Integrated Security=SSPI;" providerName="System.Data.SqlClient" />
</connectionString>
Example conn string to use with localDb

Trouble with EF6 inserts

I am in the process of Downgrading from EF7 to EF6 due to business decisions. I have looked at several examples but cannot seem to get it to work.
Here is what I have for EF 7
Context:
public class OwnerContext : DbContext
{
protected override void OnConfiguring(DbContextOptionsBuilder options)
{
options.UseSqlServer(#"Server=server\testdbs;Database=test;Trusted_Connection=True;");
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Owner>(entity =>
{
entity.ToTable("Owner");
entity.Property(e => e.Id)
.HasMaxLength(50)
.HasColumnType("varchar");
});
}
public virtual DbSet<Owner> Owner { get; set; }
}
Owner Model
public class Owner
{
public int OwnerId { get; set; }
public string Name { get; set; }
public int Age { get; set; }
}
How I use it
static void Main(string[] args)
{
using (var context = new OwnerContext())
{
var owner = new Owner
{
Name = "First Name",
Age = 4
};
context.Owner.Add(owner);
context.SaveChanges();
Console.ReadLine();
}
}
I got this to work with no issues and I get records in the data base. For EF 6 it is a little different
Here is what I have for EF6
Context
public class OwnerContext : DbContext
{
public OwnerContext(string connectionString) : base(connectionString) { }
public OwnerContext()
: this("OwnerConn")
{
}
public virtual DbSet<Owner> Owner{ get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
var owner = modelBuilder.Entity<Owner>().ToTable("Owner");
owner.Property(e => e.OwnerId)
.HasMaxLength(50)
.HasColumnType("varchar");
owner.HasKey(u => u.OwnerId);
}
}
Model
public class Owner
{
public int OwnerId { get; set; }
public string Name { get; set; }
public int Age { get; set; }
}
How I use it
static void Main(string[] args)
{
try
{
using (var context = new OwnerContext())
{
var person = new Owner
{
Name = "Test Name",
Age = 5
};
context.Owner.Add(person);
context.Entry(person).State = EntityState.Added;
context.SaveChanges();
}
}
catch (Exception exception)
{
Console.WriteLine(exception.Message);
}
Console.ReadLine();
}
ConnectionString
<connectionStrings>
<add name="OwnerConn" connectionString="Server=server\testdbs;Database=test;Trusted_Connection=True;" providerName="System.Data.SqlClient" />
</connectionStrings>
It seems to be very simple based on the tutorials. Hoever, I cant seem to get the changes to be reflected in the database. However, when I restart the console app and pull the records like this.
var rows = from a in context.Owner select a
It returns rows but I still don't see them in the DB. I'm out of ideas so hopefully someone can help.

Resources