I'm trying to add a new connection to database in an ASP.NET application, and I'm trying to use code-first initialization.
For now, that are my connection strings:
<connectionStrings>
<add name="DefaultConnection"
connectionString="Data Source=(LocalDb)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\aspnet-Auth-20211221042302.mdf;Initial Catalog=aspnet-Auth-20211221042302;Integrated Security=True"
providerName="System.Data.SqlClient" />
<add name="DriveMeConnection"
connectionString="Data Source=(LocalDb)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\DriveMe-App-20211231001122.mdf;Initial Catalog=DriveMe-App-20211231001122;Integrated Security=True;MultipleActiveResultSets=True;App=EntityFramework"
providerName="System.Data.SqlClient" />
</connectionStrings>
The first, DefaultConnection, was generated for the ASP.NET authentication, and works well.
The second, DriveMeConnection, is the database I want to create from my code-first model.
So, I created a new DbContext as usual:
public class DatabaseContext : DbContext
{
public DbSet<Azienda> Aziende;
public DbSet<ClientePrivato> ClientiPrivati;
public DbSet<Fornitore> Fornitori;
public DbSet<Auto> ParkAuto;
public DbSet<Guidatore> Guidatori;
public DbSet<Pratica> Pratiche;
public DatabaseContext() : base("name=DriveMeConnection")
{
}
}
(there's no difference if I use base("name=DriveMeConnection") or base("DriveMeConnection")).
When I am trying to read something, for example
using (DatabaseContext db = new DatabaseContext())
{
List<Fornitore> lst = db.Fornitori.ToList();
}
Fornitori table was not created. In this case, the whole database wasn't created.
I tried to add
Database.SetInitializer<DatabaseContext>(new CreateDatabaseIfNotExists<DatabaseContext>());
inside the DatabaseContext constructor, but nothing changes.
I tried to add
this.Database.CreateIfNotExists();
inside the DatabaseContext constructor, the database was created, but the tables aren't there.
I tried to force initialization with:
using (DatabaseContext db = new DatabaseContext())
{
db.Database.Initialize(force: true);
}
This creates the database, but it is still empty without tables.
What did I miss?
I finally solved, without migrations that I don't need for now, I only call this function at startup.
public static void FirstConfiguration()
{
Database.SetInitializer(new DropCreateDatabaseIfModelChanges<DatabaseContext>());
var context = new DatabaseContext();
context.Database.Initialize(true);
}
And in the DbContext, the dataset need to be properties with the get and set method:
public class DatabaseContext : DbContext
{
public DbSet<Azienda> Aziende { get; set; }
public DbSet<ClientePrivato> ClientiPrivati { get; set; }
public DbSet<Fornitore> Fornitori { get; set; }
public DbSet<Auto> ParkAuto { get; set; }
public DbSet<Guidatore> Guidatori { get; set; }
public DbSet<Pratica> Pratiche { get; set; }
public DatabaseContext() : base("name=DriveMeConnection")
{
}
}
Related
I am using asp.net boilerplate to create new project.
I have defined new service as follows:
public class Employee : Entity<int>
{
public string FName { get; set; }
public string LName { get; set; }
}
public interface IEmployeeAppService : IApplicationService
{
Employee AddEmployee(Employee emp);
List<Employee> GetAll();
}
public class EmployeeAppService : MyTestProjectAppServiceBase, IEmployeeAppService
{
private IRepository<Employee, int> _employeeRepository;
public EmployeeAppService(IRepository<Employee, int> repo)
{
_employeeRepository = repo;
}
public Employee AddEmployee(Employee emp)
{
return _employeeRepository.Insert(emp);
}
public List<Employee> GetAll()
{
return _employeeRepository.GetAllList();
}
}
I want to use the service in HomeController:
public class HomeController : MyTestProjectControllerBase
{
IEmployeeAppService service;
public HomeController(IEmployeeAppService svc)
{
service = svc;
}
}
When I run the application I get following error:
Can't create component 'MyTestProject.Services.EmployeeAppService' as it has dependencies to be satisfied.
'MyTestProject.Services.EmployeeAppService' is waiting for the following dependencies:
- Service 'Abp.Domain.Repositories.IRepository`2[[MyTestProject.Domain.Employee,
MyTestProject.Core, Version=1.0.0.0, Culture=neutral,
PublicKeyToken=null],[System.Int32, mscorlib, Version=4.0.0.0,
Culture=neutral, PublicKeyToken=b77a5c561934e089]]' which was not
registered.
How do I register the EmployeeAppService dependency with HomeController?
UPDATE
I tried the following code
IocManager.Register(typeof(IRepository<Employee, int>),
typeof(EmployeeAppService),
Abp.Dependency.DependencyLifeStyle.Transient);
but then it displays this error
There is already a component with that name. Did you want to modify the existing component instead? If not, make sure you specify a unique name.
This normally happens when your Entity (Employee in this case) is not specified in you DbContext.
Just add the following property to your DbContext class and you should be good to go:
public virtual IDbSet<Employee> Employees { get; set; }
You don't need to register application service manually. Remove the code
IocManager.Register ...
When you base from IApplicationService it's automatically registered to DI.
Error says EmployeeAppService cannot be resolved. So just like Jacques Snyman said, add the Employee entity to DbContext.
Well I was developing an ASP.NET webforms app in Visual Studio and it worked well. It has 2 SQL Server connection strings, one for ASP.NET Identity and the other for my own tables. Then I wanted to test my app on a real server. So I changed the connection strings to this:
<add name="DefaultConnection"
connectionString="Data Source=WIN-9I87AF3QUO9;Initial Catalog=aspnet-AdManager-20141230074246;Integrated Security=True"
providerName="System.Data.SqlClient" />
<add name="StracturesConnection"
connectionString="Data Source=WIN-9I87AF3QUO9;Initial Catalog=aspnet-AdManager-20141230074246;Integrated Security=True"
providerName="System.Data.SqlClient" />
Now the DefaultConnection works well. but the second one doesn't.
I get an error:
A network-realated or instance-specific error
here is the code of my DbContext
public class StructureDbContext : DbContext
{
public StructureDbContext()
: base("StructuresConnection")
{
}
public DbSet<Structure> Structures { get; set; }
public DbSet<StructureType> StructureTypes { get; set; }
public DbSet<Reservation> Reservations { get; set; }
}
and this one is the db initializer:
public class DatabaseInitializer : DropCreateDatabaseIfModelChanges<StructureDbContext>
{
protected override void Seed(StructureDbContext context)
{
Structure s = new Structure();
s.StructureTypeID = null;
s.Description = "Test";
s.CityID = 45;
s.Address = "test";
s.Price = 400;
context.Structures.Add(s);
StructureType t = new StructureType();
t.Name = "بیلبورد";
context.StructureTypes.Add(t);
}
}
}
Well the problem is a miss spelling. in the connection string I wrote "Stractures" and this is wrong! sorry for wasting your time. I should go and check why this works on visual studio!
I have been struggling to figure out a way to add the Oracle client provider name pro-grammatically. My Context class looks like this..
public class SystemFeatureContext : DbContext
{
public SystemFeatureContext(DbContextConfiguration configuration)
{
Database.Connection.ConnectionString = configuration.ConnectionString;
}
}
I get the DbContextConfiguration through my infrastructure, but trying to figure out a way to assign the provider name. If I put the whole connection string in my web.config/app.config it just works fine when passed thru the base constructor.
<connectionStrings>
<add name="Context" connectionString="DATA SOURCE=abcd;USER ID=xxxx;PASSWORD=xxxxx$1;PERSIST SECURITY INFO=True;POOLING=False;" providerName="Oracle.DataAccess.Client" />
public class SystemFeatureContext : DbContext
{
public SystemFeatureContext():base("Name=Context")
{
}
}
But my situation demand to create the context programmatically. I tried implmenting IDBConnectionFactory but it throws error that it did not find metadata.
public class OracleConnctionFactory : IDbConnectionFactory
{
private readonly string oracleConnString;
public OracleConnctionFactory(string connString)
{
oracleConnString = connString;
}
public System.Data.Common.DbConnection CreateConnection(string oracleConnString)
{
oracleConnString = this.oracleConnString;
var connectionStringBuilder = new EntityConnectionStringBuilder();
connectionStringBuilder.ProviderConnectionString = oracleConnString;
connectionStringBuilder.Provider = "Oracle.DataAccess.Client";
connectionStringBuilder.Metadata = "";
return new EntityConnection(connectionStringBuilder.ToString());
}
}
Any help would be appreciated.
I've been doing this Movies database tutorial for MVC3 with Code First, but when I try to access the /Movies page I get the error
"The network path was not found".
I don't think I missed any steps in the tutorial.
I created my Movie model
namespace Movies.Models
{
public class Movie
{
public int ID { get; set; }
public string Title { get; set; }
public DateTime ReleaseData { get; set; }
public string Genre { get; set; }
public Decimal Price { get; set; }
}
public class MovieDBContext : DbContext
{
public DbSet<Movie> Movies { get; set; }
}
}
I added the connection string as well
<add name="MovieDBContext" connectionString="Data Source=|DataDirectory|Movies.sdf" providerName="System.Data.SqlClient"/>
In the tutorial the connection string is this, but it was giving me errors trying to create the controller so I found somewhere to change it to the one above, which allows me to create the controller fine but then get the network path error.
<add name="MovieDBContext" connectionString="Data Source=|DataDirectory|Movies.sdf" providerName="System.Data.SqlServerCe.4.0"/>
Did you try?
new DbContext("MovieDBContext")
http://msdn.microsoft.com/en-us/library/gg679467(v=vs.103).aspx
Did you try to emit at least a select 1; from your code?
<system.data>
<DbProviderFactories>
<add name="SQL Server Compact Edition Data Provider"
invariant="System.Data.SqlServerCe"
description=".NET Framework Data Provider for Microsoft SQL Server Compact Edition"
type="System.Data.SqlServerCe.SqlCeProviderFactory, System.Data.SqlServerCe, Version=9.0.242.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91"/>
</DbProviderFactories>
See also Entity Framework on SQL Server CE without driver install
i think you have forgot to add
Integrated Security=SSPI
I'm trying to get my mysql data in ASP.net MVC3.
The mysql Database Name is supply_db and table name is xcart_orders.
ASP.net code is like below,
(Im just following my book, and just switch to my DB info but it does not work :( )
(I will omit using and namespace)
Web.Config File,
<add name="EFMysqlContext" connectionString="server=XXX.XXX.XXX.XX;User Id=root;pwd=xxx;Persist Security Info=True;database=supply_db"
providerName="Mysql.Data.MySqlClient" />
Abstract/IXcartOrdersRepository.cs
public interface IXcartOrdersRepository
{
IQueryable<XcartOrder> xcart_orders { get; }
}
/Concrete/EFXcartOrderRepository.cs
public class EFXcartOrdersRepository : IXcartOrdersRepository
{
private EFMysqlContext context = new EFMysqlContext();
public IQueryable<XcartOrder> xcart_orders
{
get { return context.xcart_orders; } // I thought the 'xcart_orders' should be match with db table name, isn't it?
}
}
/Entities/XcartOrder.cs
public class XcartOrder
{
[Key]
public int orderid { get; set; }
public string login { get; set; }
public string membership { get; set; }
public decimal subtotal { get; set; }
}
and In my controller,
IXcartOrdersRepository XcartOrdersRepository = new EFXcartOrdersRepository();
int orderCnt = XcartOrdersRepository.xcart_orders.Count();
then error occur, the error message say "{"Table 'supply_db.XcartOrders' doesn't exist"}"
I think I could connect to db, but couldn't get the table.
anybody know which part do I need to change?
Thank you!
can you decorate your Xcartorder class with the Table attribute to explicitly specify the desired name?
[Table("xcart_orders")]
public class XcartOrder
{
...
edit: attribute syntax