I've started to learn Entity Framework recently and I'm new. I wrote the first simple program, but it doesn't work. I tried to find solution on Google, but without result. I hope to find answer here.
ApplicationContext.cs
using Microsoft.EntityFrameworkCore;
namespace HelloApp
{
class ApplicationContext: DbContext
{
public DbSet<User> Users { get; set; }
public ApplicationContext()
{
Database.EnsureCreated();
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer("Server=(localdb)\\mssqllocaldb;Database=helloappdb;Trusted_Connection=True;");
}
}
}
Program.cs
using System;
using System.Linq;
namespace HelloApp
{
class Program
{
static void Main(string[] args)
{
using (ApplicationContext db = new ApplicationContext())
{
User user1 = new User { Name = "Tom", Age = 33 };
User user2 = new User { Name = "Alice", Age = 26 };
db.Users.Add(user1);
db.Users.Add(user2);
db.SaveChanges();
Console.WriteLine("Successfully saved!");
var users = db.Users.ToList();
Console.WriteLine("List of objects:");
foreach (User u in users)
{
Console.WriteLine($"{u.Id}.{u.Name} - {u.Age}");
}
}
}
}
}
Thanks for your help!!!
[Update] I realised that System.TypeInitializationException clarifies me, what problem happened:
The type initializer for 'Microsoft.Data.SqlClient.SNINativeMethodWrapper' threw an exception. ---> System.ComponentModel.Win32Exception: Failed to load C:\Users\Босс\Desktop\x86\SNI.dll
I was looking for on Google, but could find only one posibble explanation:
"That makes me suspect that you build it on a 64 bit system and then just transferred the files to the other machine. You need to publish the project for an x86 target to get the right native dependency resolved. Give it a try."
I have 64-bit Windows 10 on 64-bit CPU and i can't understand how to publish my project in another bit rate?
Okay, it can sound ridiculous, but all what i need was updating of NuGet package Microsoft.Data.SqlClient
Related
Lately I have some issues with Autofac.
I have an aggregate service like this:
public interface ICommonServices
{
IQueryBus QueryBus { get; }
ICommandBus CommandBus { get; }
INotificationBus NotificationBus { get; }
ILoggerFactory LoggerFactory { get; }
}
And I am registering it like this:
public class AutofacModule : Module
{
protected override void Load(ContainerBuilder builder)
{
builder.RegisterAggregateService<ICommonServices>();
}
}
And when I do:
var services = container.Resolve<ICommonServices>();
I am getting this error:
"The requested service 'Infrastructure.ICommonServices' has not been registered.
To avoid this exception, either register a component to provide the service, check for service
registration using IsRegistered(), or use the ResolveOptional() method to resolve an optional dependency."
I have many assemblies and I use Autofac modules. If I put a breakpoint in the module I see that it is called and registered. Also if I inspect Container registrations, I see that there is a registration for ICommonServices:
Activator = Object (DelegateActivator), Services = [Infrastructure.ICommonServices],
Lifetime = Autofac.Core.Lifetime.CurrentScopeLifetime, Sharing = None, Ownership = OwnedByLifetimeScope,
Pipeline = Autofac.Core.Pipeline.ResolvePipeline
If I move the registration out from AutofacModule to the main assembly, jst before the builder.Build() then all works and Autofac is abble to resolve it.
Why then the error if the service is registered? And this is not the only one.
The issue was Assembly scanning in .net core 3.1.
The old - non working way:
var assemblies= Assembly.GetExecutingAssembly()
.GetAllAssemblies()
.ToArray();
the new - WORKING one:
var l2Assemblies = Assembly.GetExecutingAssembly()
.GetAllAssembliesWithContext()
.ToArray();
I'm using the following code in my startup class to prevent errors serializing my entities which may cause circular references, but it is not working.
Why?
public partial class Startup
{
public static void ConfigureMobileApp(IAppBuilder app)
{
HttpConfiguration config = new HttpConfiguration();
new MobileAppConfiguration()
.UseDefaultConfiguration()
.ApplyTo(config);
config.MapHttpAttributeRoutes();
// Use Entity Framework Code First to create database tables based on your DbContext
Database.SetInitializer(new MobileServiceInitializer());
MobileAppSettingsDictionary settings = config.GetMobileAppSettingsProvider().GetMobileAppSettings();
config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
config.Services.Add(typeof(IExceptionLogger), new AiExceptionLogger());
if (string.IsNullOrEmpty(settings.HostName))
{
app.UseAppServiceAuthentication(new AppServiceAuthenticationOptions
{
// This middleware is intended to be used locally for debugging. By default, HostName will
// only have a value when running in an App Service application.
SigningKey = ConfigurationManager.AppSettings["SigningKey"],
ValidAudiences = new[] { ConfigurationManager.AppSettings["ValidAudience"] },
ValidIssuers = new[] { ConfigurationManager.AppSettings["ValidIssuer"] },
TokenHandler = config.GetAppServiceTokenHandler()
});
}
app.UseWebApi(config);
}
}
According to your description, I created my Azure Mobile App project to test this issue. Based on your Startup.cs, I added my apiController as follows:
[MobileAppController]
public class ValuesController : ApiController
{
[Route("api/values")]
public HttpResponseMessage Get()
{
Department sales = new Department() { Name = "Sales" };
Employee alice = new Employee() { Name = "Alice", Department = sales };
sales.Manager = alice;
return Request.CreateResponse(sales);
}
}
public class Employee
{
public string Name { get; set; }
//[JsonIgnore]
public Department Department { get; set; }
}
public class Department
{
public string Name { get; set; }
public Employee Manager { get; set; }
}
When access this endpoint, I encountered the following XML Circular Object References error:
Note: For a simple way, I removed the XML Formatter via config.Formatters.Remove(config.Formatters.XmlFormatter);. Also, you could refer to the section about preserving object references in XML from Handling Circular Object References.
After I removed XML Formatter, then I encountered the following error about object references loop in JSON:
Then, I followed this Loop Reference handling in Web API code sample, but without luck in the end. Also, I tried to create a new Web API project and found that ReferenceLoopHandling.Ignore could work as expected.
In the end, I found that if I remove the MobileAppController attribute from my
apiController, then it could work as follows:
In summary, I assumed that you could try to ignore the reference attributes with the JsonIgnore for JSON.NET, for more details you could refer to fix 3:Ignore and preserve reference attributes.
Nervicebus 4.6 Unit Testing issue
I recently discovered IWantToRunBeforeConfigurationIsFinalized to inject propertys into a handler, changed all my service code and now suddenly all my NserviceBus.Test fails.
public void run {
Configure.Instance.Configurer.ConfigureProperty<MyMessage_Handler>(h => h.MyProperty, "somevalue");
}
When i atttempt a unit test
var message = new MyMessage
{
...
...
};
Test.Handler<MyMessage_Handler>().WithExternalDependencies(m =>
{
m.PropertyA = aValue;
m.PropertyB = bValue;
})
.ExpectPublish<MyEvent>(m =>
{
Assert.That(...);
return true;
})
.OnMessage<MyMessage>(message);
I receive the following exception
TestFixture failed: SetUp : System.InvalidOperationException : Cannot
configure properties for a type that hasn't been configured yet:
at
NServiceBus.ObjectBuilder.Autofac.AutofacObjectBuilder.ConfigureProperty(Type
component, String property, Object value) in
y:\BuildAgent\work\31f8c64a6e8a2d7c\src\NServiceBus.Core\ObjectBuilder\Autofac\AutofacObjectBuilder.cs:line
114
However if i configure the bus like this, calling configurecomponent on the handler. The test framework works
This was my original method, it works fine but i prefer the approach of IWantToRunBeforeConfigurationIsFinalized to cleanly seperate the logic.
Configure.With()
.DefaultBuilder()
.PurgeOnStartup(false)
.RunCustomAction(() => Configure.Instance.Configurer.ConfigureComponent<MyMessage_Handler>(DependencyLifecycle.InstancePerUnitOfWork))
.RunCustomAction(() => {
Configure.Instance.Configurer.ConfigureProperty<MyMessage_Handler>(h => h.MyProperty, "myValue");
}
...
How can I use IWantToRunBeforeConfigurationIsFinalized , inject propertys into the handlers and continue using the Nservicebus test framework?
It seems odd to try to configure properties directly on handlers. If it's only needed by one handler, then it should be dealt with in that handler, perhaps in a static constructor in that handler class.
At any rate, you're putting yourself at the mercy of when types are loaded up and registered into the container, which isn't necessarily deterministic across different versions of NServiceBus, and clearly not when dealing with the testing framework.
Instead, what if you created a new class:
public class ReferenceValues
{
public string MyProperty { get; set; }
}
Then, you could register this type normally, from any point in the endpoint startup. Preferably, as an INeedInitialization since most of the extensibility points go away in NServiceBus 5.x and INeedInitialization is really the only game in town.
// V4 code
public class SetupReferenceValues : INeedInitialization
{
public void Init()
{
Configure.Component<ReferenceValues>(DependencyLifecycle.SingleInstance)
.ConfigureProperty(rv => rv.MyProperty, "myValue");
}
}
Then, in your handler:
public class MyHandler : IHandleMessages<MyMessage>
{
public ReferenceValues Values { get; set; }
public void Handle(MyMessage message)
{
Console.WriteLine(Values.MyProperty);
}
}
I believe this should work from the testing framework as well.
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.
When I execute my web app and try to save data into databse, this exception happens :
Model compatibility cannot be checked because the database does not
contain model metadata. Model compatibility can only be checked for
databases created using Code First or Code First Migrations.
I try lot of issue for resolve this problem , but it persist yet !!
Using migrations isn't really necessary if you're developing on your local machine. You can just set the database Initializer to drop the database always, run some code that interacts with the database, and then you'll see that the database will be recreated and the error will be gone.
Should work, that's how I do it.
delete the database manually, then restart the project with:
public class DbDataContext : DbContext
{
public IDbSet<FlightType> FlightTypes { get; set; }
public DbDataContext()
{
//Validates if database Exists or if is CompatibleWithModel
//Using when Databes is productive - use code first migrations for db changes in this case
//Database.SetInitializer(new ValidateDatabase<DbDataContext>());
//Custom Initializer - crates databse with required entries
//Using while developing
Database.SetInitializer<DbDataContext>(new DatabaseInitializer<DbDataContext>());
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
}
}
DatabaseInitializer:
public class DatabaseInitializer<T> : DropCreateDatabaseIfModelChanges<DbDataContext>
{
protected override void Seed(DbDataContext dbDataContext)
{
dbDataContext.FlightTypes.Add(new FlightType { FlightTypeNummer = "axd", Name = "AXD_LX", IsDefault = true });
base.Seed(dbDataContext);
}
}
ValidateDatabase:
public class ValidateDatabase<TContext> : IDatabaseInitializer<TContext> where TContext : DbContext
{
public void InitializeDatabase(TContext context)
{
if (!context.Database.Exists())
{
throw new InvalidOperationException("Database does not exist");
}
if (!context.Database.CompatibleWithModel(true))
{
throw new InvalidOperationException("The database is not compatible with the entity model.");
}
}
}
Are you trying to use Code-First Migrations? If so, have you run the following command in the Package Manager Console?
PM> Enable-Migrations