Record with parameterless constructor? - entity-framework

I'm trying to build a web app (ASP.NET MVC3) that uses Entity Framework, and I've once again hit a wall. It throws following exception when trying to run a foreach loop over the collection in the view:
System.InvalidOperationException: The
class 'GvG.Entities.News' has no
parameterless constructor.
Now is my question, is it possible to somehow define a parameterless constructor on my record type?
My record type at the moment looks like:
type News = {
mutable ID:int;
mutable Author:string;
mutable Title:string;
mutable Content:string }
I'm aware of that I can create a class with baking-fields etc. instead, but thats what I'm trying to avoid.

It's an old one, but I stumbled upon similar issue today, and looks like with F# 3.0 you can overcome it with [<CLIMutable>] attribute: http://msdn.microsoft.com/en-us/library/hh289724.aspx
This way you can use your F# immutable records in many scenarios when C# API requires POCO.

MSDN says "In a record type, you cannot define a constructor."
http://msdn.microsoft.com/en-us/library/dd233184.aspx

I tried to solve this (espeically for Entity Framework) during some contracting project I did for the F# team and you can find an experimental solution in F# PowerPack sources. It is not fully tested & you'd have to build it yourself. The experimental solution replaces all F# tuples and F# records in the query with other (mutable) types and then transforms results back to records/tuples.
EDIT Didn't see the mention about defining class in your question, but I'll leave the example here for others who may come here with the same issue.
There is no easy workaround. The unfortunate solution is to define a class with properties explicitly:
type News() =
let mutable id = 0
let mutable author = ""
let mutable title = ""
let mutable content = ""
member x.ID with get() = id and set(v) = id <- v
member x.Author with get() = author and set(v) = author <- v
member x.Title with get() = title and set(v) = title <- v
member x.Content with get() = content and set(v) = content <- v
That's very ugly compared to records, but it's the only way to do it in the current version of F#. It is something that the F# team is aware of, so there may be some better solution in the next version.

Related

Mixed List in Realm

If you want to define a List (an array) in realm, you something like this:
var products = List<Product>()
But how do I define a List which can contain a mixture of object types? The equivalent of an AnyObject array in Swift? I've tried:
var recentItems = List<AnyObject>()
and
var recentItems = List<Object>()
.. but these don't seem to work. Is this even possible?
Unfortunately, this isn't currently possible. This comment on the Realm Cocoa Github issue tracker explains why (Realm only supports subclassing polymorphism to a minimal degree), and contains a couple of potential workarounds.

Recognize setter invocations

I have an application where some var values ought to be published to a message queue on change. That is, if a var's setter is invoked I want this to be noticed somehow and after setting the new value I want it to be published to the MQ.
I did something like this some time ago with Perl/Moose by setting an after-modifier (doing the publishing) on methods with a certain method attribute. That solution was very elegant and required no syntactical overhead besides the additional method attribute.
What would be a good solution using Scala's (2.10) capabilities without using clumsy OO patterns?
Update: What I would like to achieve is that the code looks something like this:
#Publishable var someProperty = 42
or
domainSpecificLanguageMagic someProperty = 42
One of the challenges is that these properties might be reflectively set, so a setter-method with a different name is (probably?) not an option.
I guess the way to go is scala virtualized: it has some built in primitives that allow you to change language semantic including assignment one. It isn't stock scala , but it is quite officially supported and new release usually comes no too late after the ordinary one (in a matter of weeks). (I'm confused it with another scala framework -- LMS, AFAIS it isn't supported quite good ATM, but still should solve your problem)
You can make the property private (and give it a variant name) and define its accessor and mutator methods:
class C1(...) {
private var iProp: Int = 0
def prop: Int = iProp
/* Put additional logic associated with mutation here: */
def prop_=(newProp: Int): Unit = iProp = newProp
}

Why isn't DbSet covariant?

I have a factory function to return a DbSet(Of IItemType). The actual return type will always be an implementation IItemType, for example DbSet(Of CategoryType).
I thought covariance is supported in generics and this method would work fine, but I get an exception when I try to run my code:
Unable to cast object of type 'System.Data.Entity.DbSet1[CategoryType]' to type 'System.Data.Entity.DbSet1[IItemType]'.
DbSet<T> CANNOT be co-variant. Firstly, this is because in C#, classes cannot be co-variant...only interfaces. Secondly because DbSet<T> has both co-variant and contra-variant methods.
Take the following two examples.
DbSet<CategoryType> set = context.Set<CategoryType>();
IQueryable<IItemType> query = set.Where(x => x.Foo == Bar);
So we know for a fact that all CategoryTypes are IItemType, so we know this can always work.
However conversely try this...
DbSet<CategoryType> set = context.Set<CategoryType>();
IItemType newItemType = new ProductType();
set.Add(newItemType); // Compiler error.
Not all IItemTypes are CategoryType. So if we could cast DbSet<CategoryType> to DbSet<IItemType> we would get run time errors when adding... Since the compiler knows that this might not always work, it won't let you do the casting.
However there are interfaces that DbSet<T> does allow Co-Variance on. You can try casting it to IQueryable<IItemType> for example.
However it sounds like you are trying to query against the DbSet using a query against the interface... try the following
DbSet<CategoryType> set = context.Set<CategoryType>();
IQueryable<IItemType> cast = set.OfType<IITemType>(); //(or .Cast<>() works too)
IQueryable<IItemType> query = cast.Where(x => x ....);
It looks like they could be covariant. But there is a host of differences between in-memory programming and programming against a query provider.
For Entity Framework to materialize an object from the data store it requires its exact type and the mapping from database columns to the type's properties. An interface can represent any type and EF is not (yet) able to pick a suitable implementation itself. Maybe support for interfaces will be featured in future releases.
The same applies to casting entities to an interface in an EF query (a case I just added to my list of differences).

Self-titled field and accessor in Scala

It was empirically discovered that Scala allows name clashes for object-private variables and methods like below:
class Test {
private[this] var x = 1
def x(): String = this.x.toString
}
This code is valid at least for Scala 2.10 and produces exactly what I expect (decompiled into Java):
public class Test {
private int x;
public String x() {
return BoxesRunTime.boxToInteger(x).toString();
}
public Test() {
x = 1;
}
}
The problem is that I'm not sure if I can rely on this behavior in later Scala releases because I was not able to find an authoritative proof in the specifications that this behavior is by design. So, can anybody suggest me such a source of knowledge?
Update: My goal is to use this approach to map Hibernate data model with Scala classes. Since there is no easy way to enable Hibernate to support Scala collections, I wanted to map a Java collection in a private field which is then wrapped into a Scala collection in a self-titled accessor method. The key requirement is to keep the field and the method with the same name because I want also to preserve the logical Hibernate collection name, e.g. to reference it in HQL.
these collisions are totally normal. But keep in mind that reading your code might become a problem, since these collisions should appear (if you need that) only for getters/setters.
In other case please use clear method names like:
def xAsString():
This thread can also be helpful scala discussion on name collisions
and this naming conventions by Daniel Spewaks

Does using val with Hashtable in Scala resolve concurrency issues?

I try to avoid vars in my code where possible for easier multithreading. However there is one line of code that starts:
val positions: Hashtable[String, String] ...
I'm wondering does the val make things automagically thread safe or are there further details that I need to worry about?
By prefixing positions with a val you make it immutable. By "it" I mean the reference to the Hashtable and not the Hashtable itself and therefore by "immutable" I mean you cannot assign another Hashtable to positions.
So the Hashtable itself can change over time, but positions will always point to it. Nothing is automagically threadsafe.
It depends on which collection type you import. There's immutable.HashMap and mutable.HashMap. So immutable.HashMap in combination with a val reference would be the right one to use. That does not necessarily mean everything's threadsafe now, however.
The code from Joshua Suereth’s book ‘Scala in Depth’ posted by Jan van der Vorst is helpful as long as you don’t need to guarantee that the calls to lookUp always return the latest data. It is not appropriate if you need lookUp always to work with the latest data added by insert. For more information, please see Joshua Suereth’s comments on this discussion:
https://groups.google.com/d/topic/scala-user/ORxWFIzRb2c/discussion
You make things thread safe by synchronizing access to mutable state by using the synchronized keyword to the methods in which you access mutable state. If your hashtable is mutable you should synchronize both read and write methods. However, if you know that you will more frequently read than write you might better be using an immutable hashtable with a var position and only synchronize on the write. E.g. copied from the excellent book "Scala in Depth" by Joshua D. Suereth:
class ImmutableService[Key, Value] extends Service[Key, Value] {
var currentIndex = new ImmutableHashMap[Key,Value]
def lookUp(k : Key) : Option[Value] = currentIndex.get(k)
def insert(k : Key, v: Value) : Unit = synchronized {
currentIndex = currentIndex + ((k, v))
}
}