Composite keys problems to execute Find() - entity-framework-5

The number of primary key values passed must match number of primary key values defined on the entity.
Parameter name: keyValues
public TEntity Find(int id)
{
return _context.Set<TEntity>().Find(id);
}
Possible? I know have others ways for that, but I am interesting if is possible to use find on this table.

That`s work... this is not a better way I think, but is there
Func<Acesso_LogErro, bool> expressionPerfil = Perf => Perf.idLogErro == id;
Acesso_LogErro acesso_logerro = acesso_LogErroRepository.Where(expressionPerfil).First();

Related

ordering of Hashtable in J2ME

I have some data and I have added them to Hashtable in some orders what I want to do now is to get the data in the same order that I have entered
What is the data type that I can use?
Assuming your key is a String you could add some ordering to it and have a getter method for the sorted data. See example below:
static int order;
Hashtable map = new Hashtable();
void put (String key, Object value) {
map.put(order + key, value);
order++;
}
Enumeration getSorted() {
Enumeration keys = map.keys();
Vector sortedKeys = new Vector();
while (keys.hasMoreElements()) {
String key = (String) keys.nextElement();
insertionSort(key, sortedKeys);
}
Vector sortedData = new Vector();
keys = sortedKeys.elements();
while (keys.hasMoreElements()) {
String key = (String) keys.nextElement();
sortedData.addElement(map.get(key));
}
return sortedData.elements();
}
You can find insertionSort algorithms at http://en.wikipedia.org/wiki/Insertion_sort
A Hashtable does not retain any ordering.
If you need insertion order access see if Linked Hash Map is offered in JavaME
You can download a source code of Java SE and make work LinkedHashMap in J2ME easily by removing generics (but also you might need to perform this on it's parent classes and interfaces).
You can find LinkedHashMap for Java ME here

TableServiceContext and strongly typed table name

I have a DocumentDataServiceContext derived from TableServiceContext. Inside that class I have the following method:
public DataServiceQuery<Document> Documents
{
get
{
return this.CreateQuery<Document>("Documents");
}
}
Is there a way to get rid of the string constant passed to CreateQuery and instead obtain the table name used by CloudTableClient.CreateTablesFromModel(typeof(DocumentDataServiceContext))?
No. At the end of the day, the CreateQuery() must have the table name to query against. You can of course use convention or reflection to derive what that table name will be in another method, but at some point a string must be passed to CreateQuery.
public DataServiceQuery<T> CreateQueryByConvention<T>()
{
return this.CreateQuery<T>(typeof(T).ToString());
}

How to map enum as string in database

My table:
create table MyTable (
Id int identity(1,1) not null,
MyStatus char(2) not null
)
insert into MyTable(MyStatus) select 'A'
Class and enum:
public class MyTable
{
public virtual int Id { get; set; }
public virtual MyTableStatus MyStatus { get; set; }
}
public enum MyTableStatus
{
A,
B
}
Mapping:
public MyTableMap()
{
Id(x => x.Id);
Map(x => x.MyStatus);
}
When I execute the following test, I get System.FormatException : Input string was not in a correct format...
[Test]
public void Blah()
{
MyTable myTable = Session.Get<MyTable>(1);
Assert.That(myTable.MyStatus, Is.EqualTo(MyTableStatus.A));
}
What is the right way to map an enum to it's string representation in the database?
Edit - I am writing my application on an existing database, which I cannot modify easily because it is used by other applications also. So some fields in the database (which I would like to represent as enums in my application) are of type int and some of type char(2).
You need to create a custom IUserType to convert an enum to its string representation and back. There's a good example in C# here and an example in VB.NET for working with enums here (scroll down to implementing IUserType).
Well as far as I am aware NHibernate stores enums as string only in the db by default. I think I know what the problem here is. The way you are creating the table is incorrect.
if you are using Nhibernate use it build configuration function to create the tables instead of creating the tables manually and then you will see that your enum is stored as string.
We use enums extensively in our app and it makes sense for us to store it as strings in the db. The reasons are simple if I add a new value to an enum tom then if default values are not set then my code and my data are tightly coupled which I definitely wouldnt want.
SimpleConfig.ExposeConfiguration(c => new SchemaExport(c).Create(false, true)).BuildConfiguration();
Also instead of using char for your string can you use varchar for the property.
After the update:
Cant you guys do some kind of manipulation before you store it in the database? Thus when you want to store the new char enums write a function that generates an int value for you and store this in the propertry and now save it or if you want to make it simple the function can have a switch case.
So what you do is you dont have a get on this property that is retrieved from the db instead you add a new property in the class Status that basically has the logic of getting the appropriate enum.
Do you think thats a good idea?
Hope this helps.

Adding different object types to a c# 4.0 collection

I have a function that returns objects of different types based on the parameter passed to this function.
Is it possible to add these different object types to a collection based on some identifier in C# 4.0?
Usually we do something like this
List or List
but i want one collection which can add object of any type.
Instead of just making a List<object> like other posters are recommending, you may want to define an interface eg IListableObject that contains a few methods that your objects need to implement. This will make any code using these objects much easier to write and will guard against unwanted objects getting into the collection down the line.
Yes, it is called object. Eg:
var objlist = new List<object>();
objlist.Add(1);
objlist.Add(true);
objlist.Add("hello");
You could use object[], List<object>, ArrayList, IEnumerable, ... but if those types have a common base type it would be better to stick to a strongly typed collection.
Really your collection should be as specific as you can make it. When you say
objects of different types
Do these objects have anything in common? Do they implement a common interface?
If so you you can specialise the list on that interface List<IMyInterface>
Otherwise List<object> will do what you want.
Update
No, not really.
I'm sorry but I'm going to question your design.
If you have a collection of different objects, how do you decide how to use one of the objects?
You're going to have a large switch statement switching on the type of the object, then you cast to a specific object and use it.
You also have have a similar switch statement in your factory method that creates the object.
One of the benefits of Object Orientation is that if you design your objects correctly then you don't need to do these large "If it's this object do this.Method(), if it's that object do that.OtherMethod()".
Can I ask, why are you putting different objects into the same collection? What's the benefit to you?
If you want a collection which can add objects of any type then List<object> is the most appropriate type.
Collections in earlier versions of C# (not generics) can contain any kind of objects. If they're value type, they will be boxed into object.
When you need to use them, you can just cast it to the original type.
You may use List<Type> to hold the type information, if that's what you want. And Type[], Hashtable, etc. are also fine. You can use typeof operator to get the type or use Object.GetType().
Also check out Dynamic type.
http://msdn.microsoft.com/en-us/library/dd264736.aspx
It will basically do the same thing.
My Suggestion:
public class ParamValue
{
object value = null;
public ParamValue(object val)
{
value = val;
}
public string AsString()
{
return value.ToString();
}
public int AsInt()
{
return int.Parse(value.ToString());
}
public int? AsNullableInt()
{
int n;
if (int.TryParse(value.ToString(), out n))
{
return n;
}
return null;
}
public bool AsBool()
{
return bool.Parse(value.ToString());
}
public bool? AsNullableBool()
{
bool b;
if (bool.TryParse(value.ToString(), out b))
{
return b;
}
return null;
}
}
public class Params
{
Dictionary<string, object> paramCol = new Dictionary<string, object>();
public void Add(string paramName, object value)
{
paramCol.Add(paramName, value);
}
public ParamValue this[string paramName]
{
get
{
object v;
if (paramCol.TryGetValue(paramName, out v))
{
return new ParamValue(v);
}
return null;
}
}
}
Use param class as a collectio to your values, you can convert the return to every type you want.
You could use a Tuple of Genric Types
public Tuple<T, T> MySuperMethod()
{
int number = 1;
string text = "Batman";
return new Tuple<int, string>(number, text);
}
The .NET Framework directly supports tuples with one to seven
elements. In addition, you can create tuples of eight or more elements
by nesting tuple objects in the Rest property of a Tuple object.
https://msdn.microsoft.com/en-us/library/system.tuple(v=vs.100).aspx

Populate an enum with values from database

I have a table which maps String->Integer.
Rather than create an enum statically, I want to populate the enum with values from a database. Is this possible ?
So, rather than delcaring this statically:
public enum Size { SMALL(0), MEDIUM(1), LARGE(2), SUPERSIZE(3) };
I want to create this enum dynamically since the numbers {0,1,2,3} are basically random (because they are autogenerated by the database's AUTOINCREMENT column).
No. Enums are always fixed at compile-time. The only way you could do this would be to dyamically generate the relevant bytecode.
Having said that, you should probably work out which aspects of an enum you're actually interested in. Presumably you weren't wanting to use a switch statement over them, as that would mean static code and you don't know the values statically... likewise any other references in the code.
If you really just want a map from String to Integer, you can just use a Map<String, Integer> which you populate at execution time, and you're done. If you want the EnumSet features, they would be somewhat trickier to reproduce with the same efficiency, but it may be feasible with some effort.
So, before going any further in terms of thinking about implementation, I suggest you work out what your real requirements are.
(EDIT: I've been assuming that this enum is fully dynamic, i.e. that you don't know the names or even how many values there are. If the set of names is fixed and you only need to fetch the ID from the database, that's a very different matter - see Andreas' answer.)
This is a bit tricky, since the population of those values happens at class-load time. So you will need a static access to a database connection.
As much as I value his answers, I think Jon Skeet may be wrong this time.
Take a look at this:
public enum DbEnum {
FIRST(getFromDb("FIRST")), SECOND(getFromDb("second"));
private static int getFromDb(String s) {
PreparedStatement statement = null;
ResultSet rs = null;
try {
Connection c = ConnectionFactory.getInstance().getConnection();
statement = c.prepareStatement("select id from Test where name=?");
statement.setString(1, s);
rs = statement.executeQuery();
return rs.getInt(1);
}
catch (SQLException e) {
throw new RuntimeException("error loading enum value for "+s,e);
}
finally {
try {
rs.close();
statement.close();
} catch (SQLException e) {
//ignore
}
}
throw new IllegalStateException("have no database");
}
final int value;
DbEnum(int value) {
this.value = value;
}
}
Improving on what Andreas did, you can load the contents of the database into a map to reduce the number of database connections needed.
public enum DbEnum {
FIRST(getFromDb("FIRST")),
SECOND(getFromDb("second"));
private Map<String,Integer> map;
private static int getFromDB(String s)
{
if (map == null)
{
map = new HashMap<String,Integer>();
// Continue with database code but get everything and
// then populate the map with key-value pairs.
return map.get(s);
}
else {
return map.get(s); }
}
}
Enums are not dynamic, so the short answer is that you can't do it.
Also have a look at Stack Overflow question Dynamic enum in C#.
You need to replicate in code what is in the database (or vice-versa). See this question for some good advices.
In all the languages I know enums are static. The compiler can make some optimizations on them. Therefore the short answer is no, you can't.
The question is why you want to use an enum in this way. What do you expect?
Or in other words why not use a collection instead?

Resources