Following setup:
dotConnect for Oracle 9.5.454.0
EF 6.2.0
.NET 4.6.1
oracle 12c
We defined our models with the fluent API.
When the tabels are created is everything fine except that there are no indexes created.
[Table(nameof(Preisliste) + "n")]
public class Preisliste
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int PreislisteId { get; set; }
[Required]
[MaxLength(16)]
[Index(IsUnique = true)]
public string Name { get; set; }
}
Got the solution.
I forgot to set the initializer (did it in the context-constructor):
Database.SetInitializer(new MigrateDatabaseToLatestVersion<EntityContext, Migrations.Configuration>());
After this my indexes got created.
Related
I want to implement a change log as advised in
Dev Express XAF T474899
I am using the security system generated by the XAF new solution wizard
I have defined some business objects to store the change log information.
One of these objects stores a link to the user
public virtual User User { get; set; }
On generating the code migration I am surprised to see the Up() method add the following
RenameTable(name: "dbo.UserRoles", newName: "RoleUsers");
DropPrimaryKey("dbo.RoleUsers");
AddPrimaryKey("dbo.RoleUsers", new[] { "Role_ID", "User_ID" });
On another occasion I found the following in an Up()
RenameTable(name: "dbo.EventResources", newName: "ResourceEvents");
// lots of other stuff
DropPrimaryKey("dbo.ResourceEvents");
AddPrimaryKey("dbo.ResourceEvents", new[] { "Resource_Key", "Event_ID" });
On both occasions the code that creates the entities is a Dev Express libary.
I have cross posted this question to Dev Express Support
The Dev Express business objects are defined in DevExpress.Persistent.BaseImpl.EF;
My DbContext context refers to them as
public DbSet<Role> Roles { get; set; }
public DbSet<User> Users { get; set; }
The meta data for Role shows
The meta data for User shows
My own business classes contain
namespace SBD.JobTalk.Module.BusinessObjects
{
[NavigationItem("Configuration")]
[DisplayName("Staff")]
[DefaultProperty("Summary")]
[ImageName("BO_Employee")]
[Table("Staff")]
public class Staff : BasicBo
{
public Staff()
{
Person = new Person();
}
public virtual Person Person { get; set; }
[StringLength(100, ErrorMessage = "The field cannot exceed 100 characters. ")]
[scds.Index("IX_Staff_UserName", 1, IsUnique = true)]
public string UserName { get; set; }
[NotMapped]
public string Summary => $"{Person.FirstName} {Person.LastName}";
//public virtual User User { get; set; }
}
}
public abstract class BasicBo : IXafEntityObject
{
[Browsable(false)]
[Key]
public virtual int Id { get; set; }
public virtual void OnCreated()
{
}
public virtual void OnSaving()
{
}
public virtual void OnLoaded()
{
}
}
If I un-comment the code to have the User property inside Staff, and generate a migration, the migration Up is
public override void Up()
{
RenameTable(name: "dbo.UserRoles", newName: "RoleUsers");
DropPrimaryKey("dbo.RoleUsers");
AddColumn("dbo.Staff", "User_ID", c => c.Int());
AddPrimaryKey("dbo.RoleUsers", new[] { "Role_ID", "User_ID" });
CreateIndex("dbo.Staff", "User_ID");
AddForeignKey("dbo.Staff", "User_ID", "dbo.Users", "ID");
}
[Update]
Interestingly there are more Dev Express tables than I first thought.
The primary keys are Identity.
I think am using Standard Authentication created before Dev Express added the Allow/Deny ability (V16.1)
[Update]
When I create a new project with the above settings, here is the DbContext.
using System;
using System.Data;
using System.Linq;
using System.Data.Entity;
using System.Data.Common;
using System.Data.Entity.Core.Objects;
using System.Data.Entity.Infrastructure;
using System.ComponentModel;
using DevExpress.ExpressApp.EF.Updating;
using DevExpress.Persistent.BaseImpl.EF;
using DevExpress.Persistent.BaseImpl.EF.PermissionPolicy;
namespace XafApplication1.Module.BusinessObjects {
public class XafApplication1DbContext : DbContext {
public XafApplication1DbContext(String connectionString)
: base(connectionString) {
}
public XafApplication1DbContext(DbConnection connection)
: base(connection, false) {
}
public XafApplication1DbContext()
: base("name=ConnectionString") {
}
public DbSet<ModuleInfo> ModulesInfo { get; set; }
public DbSet<PermissionPolicyRole> Roles { get; set; }
public DbSet<PermissionPolicyTypePermissionObject> TypePermissionObjects { get; set; }
public DbSet<PermissionPolicyUser> Users { get; set; }
public DbSet<ModelDifference> ModelDifferences { get; set; }
public DbSet<ModelDifferenceAspect> ModelDifferenceAspects { get; set; }
}
}
OK, I will take a stab :) Your Up() code is trying to rename the table UserRoles to RoleUsers. This means you have a prior migration where UserRoles was the table name - probably from your DevEx stuff. This could happen if they changed their models in an upgrade. The current models are expecting RoleUsers etc. so you need to get there.
So first option is let the migration do the renaming to match the underlying model. I assume this didn't work or causes other issues?
You might be able to 'fool' entity framework into using the old tables with fluent code or annotations, but if it has new columns or relationships that won't work.
What I would do is this:
1) Create a new test project with the same references you had and
copy your context and DbSets. Point the connection string to a
new database.
2) Add a migration and script it out:
update-database -Script.
3) Examine this script a use it to create
the objects needed in your database. Migrate data from the old
tables to new if needed.
4) Remove the old tables
5) In your actual
project add a migration to resync your models:
add-migration SyncDevExUpdate -IgnoreChange, update-database
Now you will have the tables your models expect.
I have just started looking into asp mvc core. According to MS poco databases remain the same.
Now all the code below has been working flawlessly on asp mvc 4 and also everything is saved in the database; As verified by sqlserverexplorer on visual studio 2015 update 3.
I can retrieve the data but after a while or after i restart the application and try to retrieve the property it says null, although I can view the data in the database.
Things tried
reinstalled vs
reinstalled mvc core
Viewed the examples on the official documentation/tutorial site
They use ICollection instead of List but they also says that you can use either.
builder.Entity().HasMany(u => u.storymode).WithOne(c => c.user);****
in the databse context OnModelCreating method.
***This line was making it keep the relationships until the application was restarted, hence it only saved the relations which were saved after the application started and lost after it restarted.
The current behavior is that it saves the data but it is not being retrieved.
Extra points
I am saving the data via a function defined below, that function belongs to a class which is injected as per the asp.net mvc core guidelines in the ConfigureServices method in the startup class.
My poco class is
public class modelsall
{
public virtual int modelsallId { get; set; }
[Required]
public virtual string username { get; set; }
[Required]
[DisplayName("Email")]
[DataType(DataType.EmailAddress)]
public virtual string email { get; set; }
[DataType(DataType.Text)]
public virtual string title { get; set; }
[DataType(DataType.Text)]
public virtual string extra { get; set; }
[Required]
[DataType(DataType.DateTime)]
public virtual DateTime startdate { get; set; }
public virtual string imageblob { get; set; }
public virtual List<comments> comments { get; set; }
public virtual List<storyfacequotes> faceq { get; set; }
//Tried adding this in desperation
//[ForeignKey("storypages")]
//public virtual int storyId { get; set; }
public virtual List<story> pages { get; set; }
//Tried adding this after a blogpost said it might help
public virtual ApplicationUser user { get; set; }
public virtual whatisit typ { get; set; }
}
Method for creating and saving
public async Task<bool> AddMainStory(string email, modelsall modelsall)
{
ApplicationUser user = await GetUser(email);
if (user == null)
{
return false;
}
modelsall.email = user.Email;
modelsall.user = user;
_context.models.Add(modelsall);
await _context.SaveChangesAsync();
if (user.mode == null)
{
user.mode = new List<modelsall>();
}
user.mode.Add(modelsall);
await _context.SaveChangesAsync();
return true;
}
property defined in ApplicationUser
public class ApplicationUser : IdentityUser
{
public virtual List<modelsall> mode { get; set; }
}
PS: I could not find a tag for asp.net mvc core, although, mvc5 is considered mvc core according to MS.
After a lot of research and not looking into the docs properly the first time,
you need this for making relationships
builder.Entity().HasMany(u => u.storymode).WithOne(c => c.user);
**** in the databse context OnModelCreating method.
but the entire thing resets if the application restarts so not an ideal solution.
For now you can either search each time, not much effect for small applications or use asp 5 and ef6.
Here is a list of features not included in ef core as of now.
I'm creating initial migration using
Add-Migration InitialCreate
But then when I'm updating my database tables from IdentityDbContext are not created so I get exceptions.
So how do I create migration for AspNetUser tables from IdentityDbContext?
Regards teamol
You can add custom fields to your AspNetUser table in your IdentityModels.cs file.
First add your custom values ito ApplicationUser class in IdentityModels:
namespace YourProjectName.Models
{
public class ApplicationUser : IdentityUser
{
public string Email { get; set; }
public string NameSurname { get; set; }
public string ProfilePhotoRoute { get; set; }
public string Title { get; set; }
}
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext()
: base("DefaultConnection")
{
}
}
After that, enter "Add-Migration NewMigration" command in package manager console.
Finally, enter "Update-Database" command in package manager console.
If your connection string -which is stated in web.config- is true, you can update succesfully your database with this way.
I have a model like the following:
[Table("forms", Schema = "mySchema")]
public class forms
{
[Key]
public int ID { get; set; }
public string field1 { get; set; }
public string field2 { get; set; }
}
This works in MVC 3, however in MVC 4 the attribute Table in not recognized. I have the System.ComponentModel.DataAnnotations namespace included, and the dll referenced, along with EntityFramework.dll. The version of EF has changed between MVC 3 and 4. If I reference the MVC 3 EF dll, Table is recognized, however Schema is not. The reason for using the table attribute is so I can specify the schema. What am I missing?
According to msdn the TableAttribute supports the schema property.
Maybe use:
[Table(Name = "forms", Schema = "mySchema")]
I'm working on an EF Code first site, and I've written my classes and a context class, the source of which is:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Entity;
using MySite.SalesTool.Data.Entities;
using System.Data.Entity.ModelConfiguration.Conventions;
namespace MySite.SalesTool.Data
{
public class SalesToolEntities : DbContext
{
public DbSet<User> Users { get; set; }
public DbSet<UserRole> UserRoles { get; set; }
public DbSet<Job> Jobs { get; set; }
public DbSet<JobAssigner> JobAssigners { get; set; }
public DbSet<JobFile> JobFiles { get; set; }
public DbSet<JobStatus> JobStatuses { get; set; }
public DbSet<AssignedUser> AssignedUsers { get; set; }
}
}
The project builds fine, but when I go to run the site, no tables are created in the database and I get an error stating that the database can't find whichever context object I try and access, presumably because the code first has not generated any of the necessary tables.
Any ideas why it wouldn't generate any of the tables at all, and not give me any kind of error information?
Do you have an initialization strategy?
Database.SetInitializer(new DropCreateDatabaseIfModelChanges<SalesToolEntities>());
From what you subscribe it sounds like you've created the database yourself. Then you need to specify an initialization
strategy otherwise no tables/data will be added to the database and querying the database will result in an exception: {"The specified table does not exist. [ sometable ]"}