Sequence contains no matching elements - Entity Framework - c#

I looked all over Stack Overflow for this exception and found a lot of questions about it, but none that could solve my problem.
I am unit testing my application. All the tests were passing until I put an index on a column of one of my entities. I am using ABP, also.
It's worth noting that the app works fine when I run it, using SQL Server, but my unit tests use an in-memory database.
This works:
[Required]
public string Name
{
get { return PersonalInformation.Name; }
set { PersonalInformation.Name = value; }
}
This doesn't:
[Column(TypeName = "VARCHAR")]
[Index]
[Required]
public string Name
{
get { return PersonalInformation.Name; }
set { PersonalInformation.Name = value; }
}
The error "Sequence contains no elements" is thrown in a class I created that inherits from AbpIntegratedTestBase, in the first line of this method:
public void UsingDbContext(Action<UnitTestDbContext> action) {
using (var context = LocalIocManager.Resolve<UnitTestDbContext>())
{
action(context);
context.SaveChanges();
}
}
Can anyone help me with this? I'm trying to solve this for 3 days ^^"

Related

Effort Entity Framework Sequence contains not matching elements

So I've been trying to setup Effort and am not having much success. Looking on their site and people's comments it looks pretty straightforward.
I started small because I just wanted to test if it works. The error I get is
"Sequence contains no matching element"
I've added a constructor like so to the dbcontext.
public ApplicationDbContext(DbConnection connection)
: base(connection, true)
{
}
My setup like so for my test
var connection = Effort.DbConnectionFactory.CreateTransient();
var context = new ApplicationDbContext(connection );
Just a test to see if it works
context.Set<MyType>().Add(new MyType() {Description = "test"});
Class for MyType
public class MyType
{
[Key]
public byte Id { get; set; }
[Required, MaxLength(50)]
public string Description { get; set; }
}
I have also tried this with the createpersistent. Same result.
I am using ef6 code first, mvc 5, .net 462.
Found the problem I had another data model with a property containing the following annotation. It didn't like it. Commented it out and it worked.
[Column(TypeName = "XML")]

Entity Framework Code First using virtual property internally, null reference when called

I am completely new to Entity Framework. I have created a model to watch services on remote machines. Currently it looks like this:
Note: I have done my best to use understandable generic names since this is from a corporate environment.
public class RemoteService
{
[Key, Column(Order = 0)]
public string Name { get; set; }
[Key, Column(Order = 1)]
public string MachineName { get; set; }
[ForeignKey("MachineName")]
public virtual RemoteEnvironment RunningAt { get; set; }
}
public class RemoteEnvironment
{
[Key]
public string MachineName { get; set; }
public string Configuration { get; set; }
public string EnvironmentNr { get; set; }
public virtual ICollection<RemoteService> Services { get; set; }
}
With context class:
public class MyDBContext : DbContext
{
public DbSet<RemoteEnvironment> RemoteEnvironments { get; set; }
public DbSet<RemoteService> RemoteServices { get; set; }
}
This model works fine when creating the database and seeding it. The RemoteService class also contains this Version property, to get the version from the Octopus Deploy API.
private string _version = "N/A";
public string Version
{
get
{
var item = GetItemFromOctopus(Name, RunningAt.EnvironmentNr);
if (item != null)
{
_version = item.ReleaseVersion;
}
return _version;
}
set
{
}
}
This also works fine when creating and seeding the database. My issue appears when I try to grab data from the database. Something like this:
using (MyDBContext context = new MyDBContext())
{
var serviceNames = new List<string>();
foreach (RemoteService service in context.RemoteServices)
{
serviceNames.Add(service.Name);
}
}
While executing the above code I get a NullReferenceException, because RunningAt is null.
From debugging I have gathered that it is when I grab service from context.RemoteServices that it fetches all the properties. First Name, then MachineName, skips RunningAt (why? Lazy Loading?) and then tries to get Version, but since RunningAt is null, it can't.
I have tried defining the RunningAt get and set methods using
private RemoteEnvironment _runningAt
but the issue stays the same, both RunningAt and _runningAt are null while fetching data from the database.
It seems that I somehow need to load the reference to the RemoteEnvironment from the database in the get of Version. But creating a context here seems a bit much.
What else can I do? I would really like to keep Version as is. If it can't be done, I will have to make a workaround. Checking version separately, actively getting and setting it instead.
Edit 1:
I have now tried three different ways to "pre-load" the RemoteEnvironments.
First:
"Pre-loading" by getting all RemoteEnvironments from database.
using (MyDBContext context = new MyDBContext())
{
var serviceNames = new List<string>();
List<M3BEnvironment> activateEnv = db.M3BEnvvironments.ToList(); //added line
foreach (RemoteService service in context.RemoteServices)
{
serviceNames.Add(service.Name);
}
}
Still getting NullReferenceException since RunningAt is null.
Second:
Removing the virtual keyword.
[ForeignKey("MachineName")]
public RemoteEnvironment RunningAt { get; set; } // virtual keyword removed
Still getting NullReferenceException since RunningAt is null.
Third:
Using Include to force eagerly loading.
using (MyDBContext context = new MyDBContext())
{
var serviceNames = new List<string>();
var services = context.RemoteServices.Include(s => s.RunningAt).ToList();
foreach (RemoteService service in services)
{
serviceNames.Add(service.Name);
}
}
Still getting NullReferenceException since RunningAt is null.
I have even tried all combinations of the above, including all three at the same time. Still getting NullReferenceException since RunningAt is null.
I also tried going the other way, through RemoteEnvironments and including Services:
using (MyDBContext context = new MyDBContext())
{
var environments = context.RemoteEnvironments.Include(env => env.Services).ToList(); // NullRefereceException happens at this call
var serviceNames = new List<string>();
var services = context.RemoteServices.Include(s => s.RunningAt).ToList();
foreach (RemoteService service in services)
{
serviceNames.Add(service.Name);
}
}
Still getting NullReferenceException since RunningAt is null. Only this time it happens while the environments call is trying to include them.
What I want to do does not seem possible. Using the referenced RunningAt property within the Version property, because it is never loaded from the database. Not even when I force it to load the RemoteEnvironments before the call to the RemoteService and subsequently the call to Version.
What I am trying to do does not seem possible. The core issue is having a navigation property and then referencing it in another property's get or set method. This does not seem to work. I have tried turning off lazy loading, forcing loading with Include and also pre-loading the DbSet which the navigation property points to. In each and every case the navigation property reference, in my case RunningAt, has been null inside the other property's get/set method.
The Entity Framework does not seem to support referencing a navigation property inside another property. If anyone knows otherwise please tell me how. In the mean time, this will be the accepted answer.

Adding a new record by using EntityFramework

I am creating a test project in order to learn using asp.net 5 and the mvc 6 framework.
I have decided to create a simple webpage that each menu item comes from the database. To do so I have created a model like such
namespace TestTemplate.Models
{
public class SideMenuItem
{
public int Id { get; set; }
public string Level { get; set; }
public string Label { get; set; }
public string Link { get; set; }
}
}
Inside my Models folder I also have a file named `TestContext.cs'
namespace TestTemplate.Models
{
public class TestContext : DbContext
{
public DbSet<SideMenuItem> SideMenuItems { get; set; }
}
}
That is my EntityFramework DbContext class.
When trying to create a new SideMenu item by using a simple view with a form to adding all the needed data, then using my angular factory that looks like this
return $resource('/api/sidemenu/:id');
I get the error:
An exception of type 'Microsoft.Data.Entity.DbUpdateException' occurred in EntityFramework.Core.dll but was not handled in user code
Additional information: An error occurred while updating the entries. See the inner exception for details.
-->System.Data.SqlClient.SqlException: Invalid object name 'SideMenuItem'.
This error occurs on SideMenuController.cs where I define my API at the part where I am trying to Post the new item:
[HttpPost]
public IActionResult Post([FromBody]SideMenuItem sideMenuItem)
{
if (sideMenuItem.Id == 0)
{
_dbContext.SideMenuItems.Add(sideMenuItem);
_dbContext.SaveChanges(); // ERROR HERE.
return new ObjectResult(sideMenuItem);
}
else
{
var original = _dbContext.SideMenuItems.FirstOrDefault(m => m.Id == sideMenuItem.Id);
original.Level = sideMenuItem.Level;
original.Label = sideMenuItem.Label;
original.Link = sideMenuItem.Link;
_dbContext.SaveChanges();
return new ObjectResult(original);
}
}
I also should mention that before running the app i used
>dnx ef migration add initial
>dnx ef database update
I believe it has to do with me not creating my database correctly. Since I am not seeing any folder on my project that had anything to do with databases or migrations.
Why is it complaining that SideMenuItem is invalid, and how can I fix the issue?
After trying to create my database again, I noticed that I had a typo on my migration command, hence the database was not created.
The command should have been dnx ef migrations ... with an s.
A good starting point with all the commands can be found here.

Azure Storage Client v4.1 - a value of the non-primitive type was expected

I've recently upgraded my ASP.NET project (MVC5) to target Azure SDK 2.3 with Storage Library 4.1 and am encountering a strange error when I try to save anything to Table Storage.
Error:
An unhandled exception of type 'Microsoft.WindowsAzure.Storage.StorageException' occurred in Microsoft.WindowsAzure.Storage.dll
Additional information: A primitive value was specified; however, a value of the non-primitive type '' was expected.
My models go into table storage via repositories that use a TableServiceContext to add, update, delete, save.
I follow this pattern for my models:
[System.Data.Services.Common.DataServiceKey(new string[] { "PartitionKey", "RowKey" })]
public class PersistedAlert : Alert, ITableEntity
{
public string PartitionKey
{
get { return this.StudentId; }
set { this.StudentId = value; }
}
public string RowKey
{
get { return this.Id; }
set { this.Id = value; }
}
public DateTime Timestamp { get; set; }
public new int Type { get; set; } //hides Enum type in Alert base class
}
During the upgrade I needed to swap out all of my references to
System.Data.Services.*
for
Microsoft.Data.Services.*
...in addition to the OData libraries.
Has something changed internally that makes my pattern no longer valid?
Since there's nothing (yet) on this error on the net, and this is pretty much the only place it's discussed, I'll add a solution even though my context is different than yours. The error is exactly the same so I guess it originates from the same place.
For me, it was a inherited primary key that caused the problem. The primary key of the serialized entity has to be natural and not overriden. If Class has an ID property, DerivedClass will also have to declare the ID property as "new", or the ID property has to be moved from Class to DerivedClass.
Here's more detail: http://jerther.blogspot.ca/2014/12/aspnet-odata-v4-primitive-value-was.html
I do believe this is a bug and not a limitation as the inherited key works very well with Entity Framework and Fluent API.
I hope this helps and saves some hair pulling.
In the end I decided to upgrade all of the repository code to move away from the WCF based TableServiceContext which is deprecated and instead make calls via CloudTable. I can only assume something internally changed to one of the above mentioned libraries that resulted in the problem I was seeing.
In addition to changing the repository code, I also needed to update my entities to inherit from the Azure ITableEntity (I had my own flavour previously), like this:
public class PersistedAlert : Alert, Microsoft.WindowsAzure.Storage.Table.ITableEntity
{
public string PartitionKey
{
get { return this.StudentId; }
set { this.StudentId = value; }
}
public string RowKey
{
get { return this.Id; }
set { this.Id = value; }
}
public DateTimeOffset Timestamp { get; set; }
public string ETag { get; set; }
public void ReadEntity(IDictionary<string, Microsoft.WindowsAzure.Storage.Table.EntityProperty> properties, Microsoft.WindowsAzure.Storage.OperationContext operationContext)
{
Microsoft.WindowsAzure.Storage.Table.TableEntity.ReadUserObject(this, properties, operationContext);
}
public IDictionary<string, Microsoft.WindowsAzure.Storage.Table.EntityProperty> WriteEntity(Microsoft.WindowsAzure.Storage.OperationContext operationContext)
{
return Microsoft.WindowsAzure.Storage.Table.TableEntity.WriteUserObject(this, operationContext);
}
}

How do you correctly store a custom object in isolated storage using C#?

Working on a sideproject with WP8, but having trouble getting IsolatedStorage working. I have looked at dozens of posts seemingly asking the same question, but I haven't been able to get any of the solutions to work. The application is a simple task organizer where I have created my own Task Objects, one being a Summary Task and each SummaryTask containing a list of BasicTasks. I have tried using XMLSerializing only to run into problems because I was using an ObservableCollection. Thought I could change the collection to a Subclass of INotifyPropertyChanged but that didn't work either. Quite frankly, I'm still getting the hang of the different between the two anyways. So anyways, my latest attempt involves trying to use IsolatedStorage Settings and that didn't work either. Here is my class definition:
class SummaryTask : TaskItem
{
public List<BasicTask> children = new List<BasicTask>();
private string sumTaskName;
private int sumTaskId;
public SummaryTask()
{
}
public SummaryTask(string name, int id)
{
sumTaskName = name;
sumTaskId = id;
}
public string SumTaskName
{
get { return sumTaskName; }
set { sumTaskName = value; }
}
public int SumTaskId
{
get { return sumTaskId; }
set { sumTaskId = value; }
}
public void addTask(string taskName, string taskText, int taskId){
children.Add(new BasicTask(taskName, taskText, taskId));
}
public List<BasicTask> CHILDREN
{
get { return children; }
}
}
}
I create a list of this SummaryTask in a Global variable and use it throughout my pages for easy access. Here is what the beginning of my MainPage.xaml.cs file looks UPDATED:
public MainPage()
{
InitializeComponent();
BackKeyPress += OnBackKeyPressed;
if (Global.settings.Contains("list"))
{
Global.list = (List<SummaryTask>)Global.settings["list"];
}
else
{
Global.list = new List<SummaryTask>();
}
}
Guidance on the poor quality of my code and how to improve it is also accepted. Thank you.
Edit: The exception indicates that an item with the same key has already been created. The stacktrace doesn't show anything of importance in this case. I should also note that the exception is thrown after adding an object to the list and trying to save it, not while compiling.
The piece of code I am using to try to save to the Isolated Storage is here, it triggers when I navigate to MainPage.xaml:
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
resultList.SelectedItem = null;
Global.settings["list"] = Global.list;
Global.settings.Save();
}
No exceptions anymore, but exiting the app and reentering isn't pulling up any saved data.
The problem with Add is very simple to fix - just use the indexer instead, which allows you to overwrite an entry with the same name:
settings["list"] = Global.list;
That won't fix the Save call... but you'd need to give more details about what exception (not just "it tells me", the full exception details) to help us help you more.

Categories