Problems with Entity Framework Power Tools in generating view - entity-framework

I've created console application. Then I've performed Install-Package EntityFramework, setted target .net 4.0.
My simple model is
public class Abonent
{
public Abonent() {}
[Key]
public int AbonentId { get; set; }
public string Name { get; set; }
}
My dbcontext is (ModelContext.cs)
public class ModelContext : DbContext
{
public ModelContext():base(){}
public DbSet<Abonent> Abonents { get; set; }
}
Program.cs is
class Program
{
static void Main(string[] args)
{
Database.DefaultConnectionFactory = new System.Data.Entity.Infrastructure.SqlCeConnectionFactory("System.Data.SqlServerCe.4.0");
ModelContext _abonentContext = new ModelContext();
Abonent abonent=new Abonent();
_abonentContext.Abonents.Add(abonent);
_abonentContext.SaveChanges();
}
}
It works just fine, but when I do right button click on ModelContext.cs and choose Entity Framework -> Generate View and I get a message box saying "Exception has been thrown by the target of an invocation".
What I've done wrong? Is exist alternative for ef power tools? (VS 2010 SP1,Entity Framework Power Tools Beta 2)

I had this problem and solved it by Uninstalling Entity Framework Power Tools Beta 2 from the Tools -> Extensions and Updates menu.
I then restarted all visual studio 2012 instances and reinstalled it via the same menu option.
This resolved the issue on my end.
Good Luck.

problem may be you are using wrong version of Entity Framework.

Related

EF Core migration

I have a working web application (an end point) containing a few methods and connected to two tables in sql server. This application is fully implemented from scratch by myself in an ashx file and does not follow any new or old architecture, simply some methods in ashx file that are remotely called and handle requirements of client. There are shared DLLs among client and server for data handling.
For some reasons I want to upgrade client side to Dot Net core, consequently common DLL needs to be upgraded and finally the end point.
Now I'm facing the problem that EF Core only supports code first, but there are ways for scaffolding . I started with Microsoft tutorials. Then I see There are certain ways for migrating and scaffolding existing database, but I got stuck for hours in first step of using command "dotnet ef dbcontext scaffold "Data Source=..." . Then usually tutorial materials get combined with other technologies like asp.net core very fast, I need to read tons of technologies to do a simple task.
I'm worried I'm going the wrong way. there are only two tables and I can implement table structure by hand. Isn't there any sample code that I can modify it's table definitions and I can restart my project soon? If things are so hard, I will omit EF from my project and redefine the whole end point logic by text sql queries.
I can implement table structure by hand.
Great. Simply create a DbContext subtype that has a DbSet for each of your entities. The only thing scaffolding does is save you time.
Here's a complete example for SQL Server:
public class Customer
{
public int Id { get; set; }
public string Name { get; set; }
public ICollection<Order> Orders { get; } = new HashSet<Order>();
}
public class Order
{
public int CustomerId { get; set; }
public int Id { get; set; }
public Customer Customer { get; set; }
}
public class Db : DbContext
{
string connectionString = "Server=localhost; database=efcore5test; integrated security = true;TrustServerCertificate=true;";
public DbSet<Customer> Customers { get; set; }
public DbSet<Order> Orders{ get; set; }
public Db(string connectionString) : base()
{
this.connectionString = connectionString;
}
public Db() : base()
{
this.Database.SetCommandTimeout(180);
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
var constr = this.connectionString;
optionsBuilder.LogTo(Console.WriteLine);
optionsBuilder.UseSqlServer(constr, o => o.UseRelationalNulls().CommandTimeout(180).UseNetTopologySuite());
base.OnConfiguring(optionsBuilder);
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Order>().HasKey(o => new { o.CustomerId, o.Id });
base.OnModelCreating(modelBuilder);
}
}

Unable to query new table from asp.net core web application using EF 1.0

I have developed a new asp.net Core web application using Visual Studio 2015. I am at the point where I am adding user customization options by adding additional tables to my local database. However I have been unable to add whatever EF needs to query a new table correctly. I get the following error when attempting to query the table..
Applying existing migrations for ApplicationDbContext may resolve this issue
There are migrations for ApplicationDbContext that have not been applied to the database
•00000000000000_CreateIdentitySchema
Apply Migrations
In Visual Studio, you can use the Package Manager Console to apply pending migrations to the database:
PM> Update-Database
Alternatively, you can apply pending migrations from a command prompt at your project directory:
dotnet ef database update
My table is a simple table with a few varchar or nvarchar columns. The model looks something like...
namespace MyNamespace.ColorSchemes
{
public class ColorSchemesViewModel
{
[Required]
public string Id { get; set; }
[Required]
public string Name { get; set; }
[Required]
public string bc { get; set; }
}
Table looks something like this in SQL Server...
CREATE TABLE [dbo].[ColorSchemes](
[Id] [nvarchar](50) NOT NULL,
[Name] [varchar](32) NOT NULL,
[bc] [nchar](7) NOT NULL
)
I have added the table to the application context like such...
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public DbSet<ColorSchemesViewModel> Colors { get; set; }
I have also used as separate class similarly like..
public DbSet<ColorSchemes> Colors { get; set; }
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
{
}
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
// Customize the ASP.NET Identity model and override the defaults if needed.
// For example, you can rename the ASP.NET Identity table names and more.
// Add your customizations after calling base.OnModelCreating(builder);
}
}
I have added the context to a controller like this...
private ApplicationDbContext _context;
public MyController(IMemoryCache memoryCache, ILoggerFactory loggerFactory, ApplicationDbContext context)
{
_memoryCache = memoryCache;
_logger = loggerFactory.CreateLogger<ChordMVCController>();
_context = context;
}
I have tried to query the table in my controller like this...
var colorSchemes = (from c in _context.Colors
select c).ToList();
I have attempted to use the Package Manager to per instructions from the error...
PM> Update-Database
I always get this error...
System.Data.SqlClient.SqlException: There is already an object named 'AspNetRoles' in the database.
This doesn't make sense since this table is already in the database and the EF definition. How do I get my table added properly to the EF migrations so I can query it?
I was able to solve this myself...
I created a different context rather than trying to embed the dbset in the default ApplicationDbContext and also removed the onModelCreating method.
public class ColorSchemeDbContext : DbContext
{
public ColorSchemeDbContext(DbContextOptions<ColorSchemeDbContext> options) : base(options)
{
}
public DbSet<ColorScheme> ColorSchemes { get; set; }
}
Replaced the ApplicationDBContext with the new context in my controller class...
private readonly ColorSchemeDbContext _context;
public MyController(IMemoryCache memoryCache, ILoggerFactory loggerFactory, ColorSchemeDbContext context)
{
_memoryCache = memoryCache;
_logger = loggerFactory.CreateLogger<ChordMVCController>();
_context = context;
}
After that the query worked. I spent a lot of time attempting to use the EF migrations to create the tables from a class syntax. Nothing seemed to work. I was creating a new .NET CORE web application in VS 2015 with the template and using user authentication which creates the AspNetRoles tables in SqlLite once you do an update-database. It is very confusing how to add additional tables using a code first approach after that. A lot more documentation is needed regarding EF migrations with respect to managing projects over time. I see the benefits of having all of your database updates maintained from your VS project but it is not easy to understand.

ADO.NET Entity Data Model auto generated code violates Code Analysis CA2214

In a MVC 3 solution, under VS 2012, it sounds strange that you receive such message after Running Code Analysis:
It is strange because the class which is mentioned in the "DON'T" analysis was generated by VS itself (not me).
To reproduce this you can:
add ADO.NET Entity Data Model to your solution,
add your database tables (already existent in SQL Server) to your diagram,
rebuild solution, add Controllers and cshtml views (those ones are generated automatically).
run the code analysis from ANALYZE menu.
So, the question is, what could we do: Refactor the auto-generated code or ignore this message?
Below a sample of auto generated class which violates the rule CA2214:
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated from a template.
//
// Manual changes to this file may cause unexpected behavior in your application.
// Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Backoffice.Entities
{
using System;
using System.Collections.Generic;
public partial class BR_SIMUL_Supermarket_Product
{
public BR_SIMUL_Supermarket_Product()
{
this.BR_SIMUL_Supermarket_Product_Price = new HashSet<BR_SIMUL_Supermarket_Product_Price>();
}
public int product_id { get; set; }
public int category_id { get; set; }
public string product_name { get; set; }
public string product_measure { get; set; }
public bool product_active { get; set; }
public virtual BR_SIMUL_Supermarket_Category BR_SIMUL_Supermarket_Category { get; set; }
more stuff here...
Here's how I solved it permanently: http://chuckbeasley.com/blog/?p=42200
This is by design to allow for lazy loading. When you access the classs through DbContext it won't fail at run-time despite the warning. You should suppress the warnings only in those files.
You should feel free to suppress these. Take a look at this discussion on the Entity Framework codeplex site for more details.

EF Upgrade from 4.0.0 to 4.3.1 causing strange errors

I have just upgraded from EF 4.0.0 to EF 4.3.1.
I am using Visual Studio 2010 Ultimate on Windows XP updated to latest release and all Windows updates/patches applied. The database engine I'm using is SQL Server 2008 R2 Developers Edition.
The following code works perfectly under EF 4.0.0 but not under EF 4.3.1.
public class ItemBase
{
public DateTime Created { get; set; }
public int CreatedByUserID { get; set; }
public DateTime LastModified { get; set; }
public int LastModifiedByUserID { get; set; }
public User CreatedBy { get; set; }
public User LastModifiedBy { get; set; }
public ItemBase()
{
CreatedByUserID = -1;
LastModifiedByUserID = -1;
CreatedBy = null;
LastModifiedBy = null;
}
}
public class User : ItemBase
{
public int UserID { get; set; }
public string LoginName { get; set; }
public string Password { get; set; }
public string EmailAddress { get; set; }
public string Firstname { get; set; }
public string Lastname { get; set; }
public string DisplayName { get; set; }
public User() : base()
{
UserID = -1;
LoginName = String.Empty;
Password = String.Empty;
EmailAddress = String.Empty;
Firstname = String.Empty;
Lastname = String.Empty;
DisplayName = String.Empty;
}
}
protected override void OnModelCreating(System.Data.Entity.ModelConfiguration.ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<User>().Property(u => u.UserID).HasDatabaseGenerationOption(DatabaseGenerationOption.Identity);
}
The only thing that has changed is the version of Entity Framework I'm using.
I have checked the references etc and everything is as expected.
As you can see from the code above, the User class inherits from ItemBase which in turn has a reference to a User instance. The underlying User table contains all the properties from the User class and the ItemBase class (except for the two navigation properties public User CreatedBy { get; set; } and public User LastModifiedBy { get; set; })
Running this code under 4.0.0 everything works as expected, not a single problem or issue whatsoever.
BUT, when I run the same code under 4.3.1 (without any changes whatsoever to anything else, including the database I'm using) I get the following error:
"Unable to determine the principal end of an association between the types 'User' and 'User'. The principal end of this association must be explicitly configured using either the relationship fluent API or data annotations."
So I then added the following two lines to the OnModelCreating method:
modelBuilder.Entity<User>().HasRequired(u => u.CreatedBy).WithMany().HasForeignKey(k => k.CreatedByUserID);
modelBuilder.Entity<User>().HasRequired(u => u.LastModifiedBy).WithMany().HasForeignKey(k => k.LastModifiedByUserID);
I then get these strange errors:
"The provider did not return a ProviderManifestToken string."
"A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections.
(provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)"
I also noticed loads and loads of these errors in the output window:
"A first chance exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll"
However, these errors appear to be a bit of a red-herring, as the database is fine, available, and the connection string is perfect too. If I subsequently undo the changes to the OnModelCreating method I get the original error again, so I don't believe the error messages I'm getting actually reflect the underlying problem that's occurring here.
So, based on all of this, I come to the following conclusions:
There is a bug in version 4.3.1 of the Entity Framework?
The fact that my code worked under 4.0.0 without the extra two lines
in the OnModelCreating method was probably due to checks not being
made in 4.0.0 which are now subsequently being made in 4.3.1?
I need to add something extra to my configuration/code, or I'm
missing something else to make this work again under 4.3.1?
Can anyone shed some light on this for me? Its driving me nuts!
Many thanks for your time on this.
Kind Regards
Steve
It looks like you have been using a pre-release version of EF 4.1. Probably CTP4 or CTP5. This is apparent because:
ModelBuilder was renamed to DbModelBuilder before 4.1 RTM
DatabaseGenerationOption was renamed to DatabaseGeneratedOption
The exception you are seeing was introduced before EF 4.1 was RTM'ed
Given this, I'm not 100% sure what model was being created with the pre-release version you were using. With 4.1 and above the two navigation properties are detected as inverses of each other and Code First tries to make a 1:1 relationship between User and User. Code First cannot determine the principal for this relationship so rather than guessing it throws asking you to provide it.
However, looking at your model it is clear that this is not what you want anyway. It seems much more likely that you want two 1:* uni-directional navigation props--one for CreatedBy and one for LastModifiedBy. This is what you setup in your OnModelCreating call.
With the changes made to the names of the classes to match 4.1/4.3 and with the code added to OnModelCreating, your code works fine for me on EF 4.3.1.
With regard to not being able to make the connection, you say that the connection string is correct, in which case it must be a case of EF not finding it. Assuming it is in your app.config, then you need to pass the name of it to the DbContext constructor. For example:
public class MyContext : DbContext
{
public MyContext()
: base("name=MyConnectionStringName")
{
}
}
If you're using the connection string in some other way then we'll need more details on that.

How to fix "Properties whose types are collection of primitives or complex types are not supported" with EF DbContext?

I have a project containing POCO entities. A database context has been created for it using Entity Framework 4.2 and code first. This works fine, but the context needs to be exposed as an OData service which does not work.
Browsing to the OData service gives this error:
The property 'DataSubmissionItems' on type
'Lifecycle.ProgramReportSubmission.Model.ProgramReportSubmission' is
not a valid property. Properties whose types are collection of
primitives or complex types are not supported.
The data service class looks like:
public class ExceptionReportDataService : DataService<ExceptionReportEntitiesContext>
{
// This method is called only once to initialize service-wide policies.
public static void InitializeService(DataServiceConfiguration config)
{
config.SetEntitySetAccessRule("*", EntitySetRights.AllRead);
config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V2;
config.UseVerboseErrors = true;
}
}
The EF context class looks like:
public class ExceptionReportEntitiesContext : DbContext
{
public DbSet<ExceptionReport> ExceptionReports { get; set; }
public ExceptionReportEntitiesContext()
: base(DynamicConfig.GetAppSettingValue("DB_CONN_STRING_LIFECYCLE"))
{
}
}
The POCO entities look like:
namespace WBRT.ProgramData.Lifecycle.ExceptionReportModel
{
public class ExceptionReport
{
public virtual Guid ExceptionReportID { get; set; }
public virtual Lifecycle.ProgramReportSubmission.Model.ProgramReportSubmission ReportSubmission { get; set; }
}
}
namespace Lifecycle.ProgramReportSubmission.Model
{
public class ProgramReportSubmission
{
public Guid ProgramReportSubmissionId { get; set; }
public virtual ICollection<DataSubmissionItem> DataSubmissionItems { get; set; }
}
public class DataSubmissionItem
{
public Guid DataSubmissionItemId { get; set; }
}
}
What I've tried:
Setting DataServiceKey on the DataSubmissionItem class
Setting ProxyCreationEnabled to false on the ExceptionReportEntitiesContext constructor as well as in the data service
Overriding OnModelCreating and removing the IncludeMetadataConvention
Overriding OnModelCreating and setting modelBuilder.Entity<ProgramReportSubmission.Model.ProgramReportSubmission>().Ignore(prs => prs.DataSubmissionItems);
Note: I can't introduce a dependency on the EntityFramework DLL in the POCO entities project as this affects referencing projects that still run .NET 3.5.
Anyone know how to resolve this error?
THe RTM version of WCF DS doesn't support these kind of properties. But the latest CTP does. http://blogs.msdn.com/b/astoriateam/archive/2011/10/13/announcing-wcf-data-services-oct-2011-ctp-for-net-4-and-silverlight-4.aspx.
On the other hand, the fact that you get such an error probably means that WCF DS doesn't recognize the provider as EF, and istead works with it as with a reflection provider. So even the latest CTP won't really fix that problem.
WCF DS currently only recognizes EF provider if the T in DataService is ObjectContext or derived type. The typical workaround for EF Code First is to define the service as DataService and then override the CreateDataSource method on it and return the ObjectContext implementation from your DbContext. See this article about how to do that (it's about EF 4.1, but I think the same will apply to 4.2 as well): http://social.technet.microsoft.com/wiki/contents/articles/5234.aspx. You can skip down to the part about WCF DS.