RepoDb cannot find mapping configuration - orm

I'm trying to use RepoDb to query the contents of a table (in an existing Sql Server database), but all my attempts result in an InvalidOperationException (There are no 'contructor parameter' and/or 'property member' bindings found between the resultset of the data reader and the type 'MyType').
The query I'm using looks like the following:
public Task<ICollection<MyType>> GetAllAsync()
{
var result = new List<MyType>();
using (var db = new SqlConnection(connectionString).EnsureOpen())
{
result = (await db.ExecuteQueryAsync<MyType>("select * from mytype")).ToList();
}
return result;
}
I'm trying to run this via a unit test, similar to the following:
[Test]
public async Task MyTypeFetcher_returns_all()
{
SqlServerBootstrap.Initialize();
var sut = new MyTypeFetcher("connection string");
var actual = await sut.GetAllAsync();
Assert.IsNotNull(actual);
}
The Entity I'm trying to map to matches the database table (i.e. class name and table name are the same, property names and table column names also match).
I've also tried:
putting annotations on the class I am trying to map to (both at the class level and the property level)
using the ClassMapper to map the class to the db table
using the FluentMapper to map the entire class (i.e. entity-table, all columns, identity, primary)
putting all mappings into a static class which holds all mapping and configuration and calling that in the test
providing mapping information directly in the test via both ClassMapper and FluentMapper
From the error message it seems like RepoDb cannot find the mappings I'm providing. Unfortunately I have no idea how to go about fixing this. I've been through the documentation and the sample tutorials, but I haven't been able to find anything of use. Most of them don't seem to need any mapping configuration (similar to what you would expect when using Dapper). What am I missing, and how can I fix this?

Related

Updating and inserting in an OData service

I have a Xamarin.Forms Visual Studio solution, into which I installed the “Simple.OData.Client” package with NuGet. I have the URI of an OData service and I want to load items from the table “Persons”, in which the base element type is “Person” and which contains instances of the class “Customer”, which inherits from the class “Person”, as I can see when opening the URI to which I append “/$metadata”.
<Schema xmlns="http://schemas.microsoft.com/ado/2009/11/edm" Namespace="A">
...
<EntityType Name="Person" Abstract="true">
...
<EntityType Name="Customer" BaseType="A.Person">
...
<EntityContainer Name="Model" m:IsDefaultEntityContainer="true">
...
<EntitySet Name="Persons" EntityType="A.Person"/>
...
I create an instance of the service:
ODataClient clientSimple = new ODataClient("http://.../.../odata.v3/default");
I load items from the data table:
System.Collections.Generic.IEnumerable<System.Collections.Generic.IDictionary<string, object>> persons = await clientSimple.For("Persons").FindEntriesAsync();
The items are returned as dictionaries where the keys are the property names and the values are the property values. I see that the properties from the “Person” entity type as well as those added in the derived “Customer” type are present.
I know that there is also a possibility of the typed syntax:
var personsTyped = await clientSimple.For<Person>().FindEntriesAsync();
However, I do not know where to get the definition of the “Person” class so that I can use it here as the generic type parameter.
Then I want to modify an entry in the OData service:
await clientSimple.For("Persons").Key(1).Set(new { FirstName = "Johnny" }).UpdateEntryAsync();
This works as long as I only update a property defined in the “Person” entity type, but trying to modify a property added in the “Customer” entity type raises an exception:
await clientSimple.For("Persons").Key(1).Set(new { FirstName = "Johnny", SalesPerson = "..." }).UpdateEntryAsync();
[Simple.OData.Client.UnresolvableObjectException] No property or association found for [SalesPerson].
Trying to insert a new item also fails:
var newObjectCreated = await clientSimple.For("Persons").Set(new { FirstName = "...", ... }).InsertEntryAsync();
[Simple.OData.Client.WebRequestException] Internal Server Error
How can I solve this so that I can update all properties and insert new items?
There are several source of information that might be useful for you. First, I suggest you have a look at Simple.OData.Client wiki pages, in particulary pages that give examples of how to modify data:
https://github.com/object/Simple.OData.Client/wiki/Modifying-data
Then there are plenty of examples that you can get from the project tests, look here for example:
https://github.com/object/Simple.OData.Client/blob/master/Simple.OData.Client.Tests.Net40/InsertTests.cs
https://github.com/object/Simple.OData.Client/blob/master/Simple.OData.Client.Tests.Net40/InsertTypedTests.cs
https://github.com/object/Simple.OData.Client/blob/master/Simple.OData.Client.Tests.Net40/UpdateTests.cs
https://github.com/object/Simple.OData.Client/blob/master/Simple.OData.Client.Tests.Net40/UpdateTypedTests.cs
And if you want to use typed syntax (which I recommend) you should define your entity types yourself, currently Simple.OData.Client doesn't have any entity type generation utility.

ASP.NET MVC 4 Deferred query execution not retrieving data from database

I am new in ASP.NET MVC 4. In my project I am using Code First technique in of EF. I want to retrieve some data from database and I used following code for this :
List<SelectListItem> ls = new List<SelectListItem>();
var lm = from m in db.BOs //fetch data from database
select m;
foreach (var temp in lm)
{
ls.Add(new SelectListItem() { Text = temp.Name, Value = temp.Id.ToString() });
}
But when execution pointer move inside foreach it immediately come back out of the loop showing return ls value Count = 0. Code does not giving me any error while running that's why I am not getting where is going wrong.
UPDATE: I found something new this problem. When I kept mouse pointer over var lm; it shows me query and in query table name in FROM clause is not that one in my SQL database. My SQL table name is BO and in query it is taking BOes. I don't know from where this name is coming. So How I overcome this??
decorate your BO class with Table("BO") to specify the table name (attribute is in System.ComponentModel.DataAnnotations.Schema namespace)
[Table("BO")]
public partial class BO
{
...
Write following code inside DbContext class :
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
}
The modelBuilder.Conventions.Remove statement in the OnModelCreating method prevents table names from being pluralized. If you didn't do this, the generated tables would be named Students, Courses, and Enrollments. Instead, the table names will be Student, Course, and Enrollment. Developers disagree about whether table names should be pluralized or not. This tutorial uses the singular form, but the important point is that you can select whichever form you prefer by including or omitting this line of code.

How to display only specific columns of a table in entity framework?

how to display the some specific columns of table instead of whole table in entity framework.
using (DataEntities cxt = new DataEntities())
{
notes note = cxt.notes.Where(no => no.id == accID).SingleOrDefault();
return notes;
}
For this purpose, I would suggest you to make use of ViewModel like following :-
notes note = cxt.notes.SingleOrDefault(no => no.id == accID);
var model = new YourViewModel // Your viewModel class
{
ID = note.ID,
PropertyOne = note.PropertyOne, // your ViewModel Property
PropertyTwo = note.PropertyTwo
};
You can do this with QueryView.
This implies editing your model directly in XML as there is no designer support for this, but you will get an independant entity with less fields than the original one.
Advantages:
You can then query data base for this truncated entity directly (you will get only fields you need from the data base - no need to get whole entity from DB and trancate it in code)
It is good in scenarios where you want to send this truncated entity to the
client
with WCF to minimize traffic (e.g. when building big lists on client
that basically need only name and ID and no other entity specific
information).
Disadvantages:
This QueryView-based entity is read only. To make it writeable you will have to add r/w functionality yourself

Auto generated linq class is empty?

This is a continuation of my previous question: Could not find an implementation of the query pattern
I'm trying to insert a new 'Inschrijving' into my database. I try this with the following code:
[OperationContract]
public void insertInschrijving(Inschrijvingen inschrijving)
{
var context = new DataClassesDataContext();
context.Inschrijvingens.InsertOnSubmit(inschrijving);
dc.SubmitChanges();
}
But the context.Inschrijvingens.InsertOnSubmit(inschrijving); gives me the following error:
cannot convert from 'OndernemersAward.Web.Service.Inschrijvingen' to 'OndernemersAward.Web.Inschrijvingen'
I call the method in my main page:
Inschrijvingen1Client client = new Inschrijvingen1Client();
Inschrijvingen i = new Inschrijvingen();
client.insertInschrijvingCompleted += new EventHandler<System.ComponentModel.AsyncCompletedEventArgs>(client_insertInschrijvingCompleted);
client.insertInschrijvingAsync(i);
But as you can see there appears to be something wrong with my Inschrijvingen class, which is auto generated by LINQ. (Auto generated class can be found here: http://pastebin.com/QKuAAKgV)
I'm not entirely sure what is causing this, but I assume it has something to do with the auto generated class not being correct?
Thank you for your time,
Thomas
The problem is that you've got two Inschrijvingen classes - one in the OndernemersAward.Web.Service namespace, and one in the OndernemersAward.Web namespace.
You either need to change the codebase so that you've only got one class, or you need to convert from one type to the other.

NHibernate - How do I change schemas during run time?

I'm using NHibernate to connect to an ERP database on our DB2 server. We have a test schema and a production schema. Both schemas have the same table structure underneath. For testing, I would like to use the same mapping classes but point NHibernate to the test environment when needed and then back when in production. Please keep in mind that we have many production schemas and each production schema has an equivalent test schema.
I know that my XML mapping file has a schema property inside it, but since it's in XML, it's not like I can change it via a compiler directive or change the schema property based on a config file.
Any ideas?
Thank You.
No need to specify schema in the mappings: there's a SessionFactory-level setting called default_schema. However, you can't change it at runtime, as NHibernate pregenerates and/or caches SQL queries, including the schema part.
To get what I wanted, I had to use NHibernate.Mapping.Attributes.
[NHibernate.Mapping.Attributes.Class(0, Table = “MyTable”, Schema = MySchemaConfiguration.MySchema)]
In this way, I can create a class like MySchemaConfiguration and have a property inside of it like MySchema. I can either set the property's value via a compiler directive or get it through a configuration file. This way I only have to change the schema in one place and it will be reflected throughout all of the other mappings.
I have found following link that actually fixes the problem.
How to set database schema for namespace in nhibernate
The sample code could be
cfg.ClassMappings.Where(cm => cm.Table.Schema == "SchemaName")
.ForEach(cm => cm.Table.Schema = "AnotherSchemaName");
This should happen before you initialize your own data service class.
#Brian, I tried NHibernate.Mapping.Attributes, the attribute value you put inside should be a constant. So it could not be updated during run time. How could you have set the property's value using a parameter value in configuration file?
The code to fix HBM XML resources.
// This is how you get all the hbm resource names.
private static IList<string> GetAllHbmXmlResourceNames(Assembly assembly)
{
var result = new List<string>();
foreach (var resource in assembly.GetManifestResourceNames())
{
if (resource.EndsWith(".hbm.xml"))
{
result.Add(resource);
}
}
return result;
}
// This is how you get the stream for each resource.
Assembly.Load(assembly).GetManifestResourceStream(name)
// What you need to do next is to fix schema name in this stream
// Replacing schema name.
private Stream FixSchemaNameInStream(Stream stream)
{
StreamReader strStream = new StreamReader(stream);
string strCfg = strStream.ReadToEnd();
strCfg = strCfg.Replace(string.Format("schema=\"{0}\"" , originalSchemaName), string.Format("schema=\"{0}\"" , newSchemaName));
return new MemoryStream(Encoding.ASCII.GetBytes(strCfg));
}
Take a look at SchemaUpdate.
http://blogs.hibernatingrhinos.com/nhibernate/archive/2008/04/28/create-and-update-database-schema.aspx