I have generated a LinqtoSQL mapping xml file, which I have a valid XSD schema that I check to make sure the XML is correct.
Now I want to check that the field type match the Model/Interface
for example:
checking that the nullable fields are nullable
that int are int etc
anyone got any ideas if I can do this?
One way I have found is to just pass in a new object without setting anything:
[Test]
[Rollback]
public void Should_take_a_Document_with_nulls()
{
// Arrange
var repository = GetRepository();
var contact = new Contact();
// Act
repository.Save(contact);
// Assert
}
Related
I want to create a JSON file for use as part of a simple web prototyping exercise. LinqPAD is perfect for accessing the data from my DB in just the shape I need, however I cannot get it out as JSON very easily.
I don't really care what the schema is, because I can adapt my JavaScript to work with whatever is returned.
Is this possible?
A more fluent solution is to add the following methods to the "My Extensions" File in Linqpad:
public static String DumpJson<T>(this T obj)
{
return
obj
.ToJson()
.Dump();
}
public static String ToJson<T>(this T obj)
{
return
new System.Web.Script.Serialization.JavaScriptSerializer()
.Serialize(obj);
}
Then you can use them like this in any query you like:
Enumerable.Range(1, 10)
.Select(i =>
new
{
Index = i,
IndexTimesTen = i * 10,
})
.DumpJson();
I added "ToJson" separately so it can be used in with "Expessions".
This is not directly supported, and I have opened a feature request here. Vote for it if you would also find this useful.
A workaround for now is to do the following:
Set the language to C# Statement(s)
Add an assembly reference (press F4) to System.Web.Extensions.dll
In the same dialog, add a namespace import to System.Web.Script.Serialization
Use code like the following to dump out your query as JSON
new JavaScriptSerializer().Serialize(query).Dump();
There's a solution with Json.NET since it does indented formatting, and renders Json dates properly. Add Json.NET from NuGet, and refer to Newtonsoft.Json.dll to your “My Extensions” query and as well the following code :
public static object DumpJson(this object value, string description = null)
{
return GetJson(value).Dump(description);
}
private static object GetJson(object value)
{
object dump = value;
var strValue = value as string;
if (strValue != null)
{
var obj = JsonConvert.DeserializeObject(strValue);
dump = JsonConvert.SerializeObject(obj, Newtonsoft.Json.Formatting.Indented);
}
else
{
dump = JsonConvert.SerializeObject(value, Newtonsoft.Json.Formatting.Indented);
}
return dump;
}
Use .DumpJson() as .Dump() to render the result. It's possible to override more .DumpJson() with different signatures if necessary.
As of version 4.47, LINQPad has the ability to export JSON built in. Combined with the new lprun.exe utility, it can also satisfy your needs.
http://www.linqpad.net/lprun.aspx
How do I check that the model is correct for an object read from the database.
var myModelObject = theDB.myDbContext.myModelObject.Find(1234);
Now I would like to control if it is correct according to the rules / attributy in the model... but how?
It is expected that data read from database are correct according to validation rules because that validation rules also defines the mapping. Inconsistency can lead in some cases to exception in object materialization.
If you want to executed validation based on data annotations manually you can use:
using System.ComponentModel.DataAnnotations;
var results = new List<ValidationResult>();
var context = new ValidationContext(myModelObject, null, null);
bool isValid = Validator.TryValidateObject(myModelObject, context, results, true);
I want to create a property on my LINQ To SQL designer-generated class that gets and sets a formatted type, like that:
public partial ALinqClass
{
public string formatedValue
{
get { return formatValue(TheValue); }
set { TheValue = RemoveFormating(value); }
}
}
TheValue is the property generated by the Linq designer.
How do I decorate public string formatedValue so I can bind it to controls on my form?
For example: When I use Visual Studio to create a Object Data Source from my linq object/class all properties linq generated are present on the Object data Source, but formatedValue is not.
Why ?
WHY ?
WHHHHHHHHY ????????!!!!!
Thank you.
Fábio
Linq-to-SQL generated entities are declared as partial classes so you should be able to create another file and add custom properties to the same partial class. This is so if you have to regenerate the classes, your additions to the entities are still available in a different file.
Also as long as these properties are public, you should be able to databind them just like generated properties.
For Windows Forms Databinding, you need either
A datasource, which is derived from Control.
An intermediate component, BindingSource, acting as link between the LinqToSql datasource and bound controls.
I'll outline how to use BindingSource.
private BindingSource binding1;
private YourDataContext context;
void Form1_Load(object sender, EventArgs e) {
// initialize the data context
context = new YourDataContext();
// initialize the BindingSource
binding1 = new BindingSource();
binding1.DataSource = context.YourObjects;
// bind controls to BindingSource
listBox1.DataSource = binding1;
listBox1.DisplayMember = "Name";
}
Obviously, this short sample is not complete, but should give you an idea on how to start. Further information can be found at Data Binding and Windows Forms.
Mark
I think this is the answer I wanted. Linq must have a few more classes and inheritances, but I think this will do.
http://msdn.microsoft.com/en-us/library/system.componentmodel.bindableattribute.aspx
[Bindable(true)]
public int MyProperty
{
get {
// Insert code here.
return 0;
}
set {
// Insert code here.
}
}
In the Play framework i have a few models that have fields which are object references to other models. When i use renderJSON, i don't want those object references to be included. Currently for my needs i create a separate view model class which contains the fields i want, and in the controller i create instances of this view class as needed. Ideally i would like to be able to use the model class itself without having to write the view class.
Is there a way to annotate a field so that it will not be serialized when using renderJSON?
because play uses Gson for its Json serialization you can try the following:
public static void test()
{
Object foo = new SomeObject("testData");
Gson gson = new GsonBuilder()
.excludeFieldsWithModifiers(Modifier.TRANSIENT)
.create();
renderJSON(gson.toJson(foo));
}
now each field marked as transient will not be serialized. There is also another (better) way. You can use the com.google.gson.annotations.Expose annotation to mark each field you want to serialize.
public static void test()
{
Object foo = new SomeObject("testData");
Gson gson = new GsonBuilder()
.excludeFieldsWithoutExposeAnnotation()
.create();
renderJSON(gson.toJson(foo));
}
Using FlexJSON with play is another option, explained in this article: http://www.lunatech-research.com/archives/2011/04/20/play-framework-better-json-serialization-flexjson
Not sure why no one has written the most direct solution to this answer so I will do it here:
Simply mark the fields you do not want serialized via Gson as transient.
Here's an example:
public class Animal
{
private String name = "dog";
transient private int port = 80;
private String species = "canine";
transient private String password = "NoOneShouldSeeThis";
}
None of the items which are marked transient will be serialized.
When deserialized they will be set to their default (class default) values.
Resulting JSON will look like the following:
{"name":"dog","species":"canine"}
For more information on transient you can see the SO
Why does Java have transient fields?
I would override renderJSON to check a the field name against a member array of serialization exclusions.
I have been trying out both Linq to Sql and EF in my ASP.NET MVC application. After switching to EF I realized my XML/JSON serialization output has extra cruft.
XML:
<Test xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<EntityKey>
<EntitySetName>Persons</EntitySetName>
<EntityContainerName>PersonEntities</EntityContainerName>
<EntityKeyValues>
<EntityKeyMember>
<Key>Id</Key>
<Value xsi:type="xsd:int">1</Value>
</EntityKeyMember>
</EntityKeyValues>
</EntityKey>
<Id>1</Id>
<Name>John</Name>
</Test>
JSON:
{"Id":1,"Name":"John","EntityState":2,"EntityKey"{"EntitySetName":"Persons","EntityContainerName":"PersonEntities","EntityKeyValues":[{"Key":"Id","Value":1}],"IsTemporary":false}}
Instead I would just like my output to be:
{"Id":1, "Name":"John"}
My EF query to retrieve the object is:
Tests.First(t => t.Id == testId);
You can shape the JSON result in your controller like this:
public JsonResult Person(int id)
{
var person = PersonRepository.FindByID(id);
var result = new { Id = person.Id, Name = person.Name };
return Json(result);
}
This will limit the DTO which is serialized to contain only the values you want.
Edit:
As a paritial answer to your comment question; you can create a simpler PersonViewModel class (DTO) that you can map the properties to. As John Saunders mentioned in his answer Automapper is a nice way to simplify the copying of the property values out of the EF Person instance:
The modified Action method may look like this:
public JsonResult Person(int id)
{
var person = PersonRepository.FindByID(id);
var dto = Mapper.Map<Person, PersonViewModel>(person);
return Json(dto);
}
The only other option I can think of is to use reflection to modify the DataMemberAttributes on the Person entity to suppress the EntityKey property.
Another approach to work around this is to use the JavascriptSerializer's ScriptIgnore attribute and create a partial class for the object in question, new'ing up the EntityKey, EntityState properties and adding a ScriptIgnore attribute to them:
public partial class Person
{
[ScriptIgnore]
public new System.Data.EntityKey EntityKey { get; set; }
[ScriptIgnore]
public new System.Data.EntityState EntityState { get; set; }
}
When the Person class is serialized via JavascriptSerializer, it will ignore those properties. However, this would not be practical because EF uses the state info to keep track of objects and this would wreak havoc.
If there were a way to dynamically add properties, it would eliminate the need to override those properties just to add a [ScriptIgnore] attribute. But, since there is no way to dynamically add attributes, this solution may not be that useful.
So far, the best technique I've found involves code generation. I did this on one project that was using the Service Factory, but you could do the same "by hand" using T4 Text templates directly.
Also, keep an eye on AutoMapper. It's still new enough that I consider it to be emerging technology, but I'm hoping it will emerge soon!