Good day!
I have created an EF model from database using database first aproach,
and added myself several read only properties to entity class generated by EF which are not in database.
Every time I update my model adding data from new tables
I loose properties created, so I have to recreate them.
As an example in database I have property isFemale but in my class I've created
public string Gender
{
get
{
if(isFemale) return "female";
else return "male";
}
}
My question is there a way to update the model from database, leaving properties generated by me?
Thank you!
Add the properties on another Partial Class instead of the generated class. For example, if your generated class is of type Person, define another Partial class in the same project with the same namespace:
public partial class Person
{
public string Gender
{
get
{
if(isFemale) return "female";
else return "male";
}
}
}
Using partial class will solve your problem but:
All parts of partial class must be defined in the same assembly
Properties from your partial part are not persisted to the database
Properties from your partial part cannot be used in linq-to-entities
queries
read more
You could make your class partial and seperate it in two files, this is the way I use it with DatabaseFirst.
public partial class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
public partial class Person
{
public string FullName {
get
{
return FirstName + " " + LastName;
}
}
}
Related
I have developed my first WPF applicationa (tryingt) to use MVVM. I'm still learning and would appreciate the following questions answered:
Should I keep TestReportItem class in Repository class library or move it to it's own class library?
My ViewModel does not reference a Model. It refererences the class TestReportItem. I display the TestReportItem using XAML and a datatemplate to access a string field "Title". Is this acceptable/best practice?
TestReportItem
public class TestReportItem
{
public string Title { get; set; } = string.Empty;
public string SubTitle { get; set; } = string.Empty;
public bool HasTable { get; set; }
public string Reference { get; set; } = string.Empty;
public bool HasAdditionalInformation { get; set; }
}
TestReportItemRepository
public interface ITestReportItemRepository
{
List<TestReportItem> GetAllTestReportItems();
TestReportItem GetByName(string testName);
}
XMLTestReportItemRepository
public class XMLTestReportTestStandardRepository : ITestReportItemRepository
{
private string _filePath;
public string FilePath
{
get { return _filePath; }
set { _filePath = value; }
}
public XMLTestReportTestStandardRepository(string sourceFilePath)
{
FilePath = sourceFilePath;
}
public TestReportItem GetByName(string testName)
{ ... }
public List<TestReportItem> GetAllTestReportItems()
{ ... }
MVVM is a rule of thumb and not a dogma; meaning its really flexible. Originally MVVM was based off of the three tiered data organization system. View/Business layer/DB layer. And in a sense, it is just that.
Should I keep TestReportItem class in Repository class library or move it to it's own class library?
Whether your classes reside with the main project or in an external class library is up to the design. If the design calls for reuse between different projects, then yes extract it. Otherwise being external does not add any value except in separation of work.
Remember that an external library is in a sense a different namespace to structure your code.
My ViewModel does not reference a Model. It refererences the class TestReportItem.
As to TestReportItem it is a Model. Just because it has/may have methods and operations is moot. If one needs create partial class files where the model esque properties are contained in one partial and the operations et all are in another partial are fine and one achieves separation. But that is optional
datatemplate to access a string field "Title". Is this acceptable/best practice?
Does Title get derived or generated by its being in the class. If it does, then yes, if not, place Title on the main VM and extract/build it in the getter of Title.
I want to add a new property on my class, make it strongly typed so I can use it in my views and controllers, I've tried to inherit the properties, but Entity Framework or C# throws me errors...
I have this class:
public class Patient
{
public int Id { get; set; }
public string Message { get; set; }
public string FirstName { get; set; }
.....
}
which has a lot more properties in it, but shortened here.
I have a razor view, which is uses 'Patient' as it's model
using model Project.Models.Patient
So I had completed my view (or so I thought) and was asked to add functionality in the view. The functionality is to send a POST using a form of a 'Message' (a simple textarea in html). I've already got all the details I want, but this new 'Message'
So I thought, because I don't want this field in the database I could add it like this:
public class Patient
{
public int Id { get; set; }
public string Message { get; set; }
public string FirstName { get; set; }
[NotMapped]
public string Message { get; set; }
.....
}
But I'm not a fan of this, it doesn't relate to the Patient in any other way.
So I thought I could change my model in razor to something like this:
#model Project.Models.DTOs.PatientMessage
and inherit the Patient class and all it's properties (so I don't have to retype and copy past the fields again) and the new PatientMessage class would look like this:
public class PatientMessage : Patient
{
public string Message { get; set; }
}
But when I refresh my application, I receive a message stating the Application Database Context has changed, and I have to update this. I don't want to update my database, and I can't really see why I need to, it's an extra field which I don't want to include in my database.
So then I decided to make this class an 'abstract' class
public abstract class PatientMessage : Patient
{
public string Message { get; set; }
}
When I refreshed my page this time, I saw no need to update the Database, great I thought, and when I went near a page where the model was
#model Project.Models.Patient
I received this message
The abstract type 'Project.Models.DTOs.PatientMessage' has no mapped descendants and so cannot be mapped. Either remove 'Project.Models.DTOs.PatientMessage' from the model or add one or more types deriving from 'Project.Models.DTOs.PatientMessage' to the model.
MY QUESTION
Can I include this one field, without placing it on the Patient class, ideally without having to update models in my razor views, or would I have to change the models in the views and controllers and update the information to include the message and map all the details from a 'PatientMessage' to a 'Patient'
Please let me know if you need any further information.
Regards
I have 2 Models. First one is created by EF and looks like:
public partial class PrinterMapping
{
public string MTPrinterID { get; set; }
public string NTPrinterID { get; set; }
public string Active { get; set; }
}
I created the second one (nothing to do with any database table) and looks like:
public class ExceptionModel
{
public string ExceptionMessage { get; set; }
public ExceptionModel(string exceptionMessage)
{
ExceptionMessage = exceptionMessage;
}
}
In my Index and Create views, the model that is automatically being passed is PrinterMapping. I wish to output ExceptionMessage property of the ExceptionModel model after populating it in a relevant way after saving to the table accessed by PrinterMapping. So in my Create controller, I am doing:
ExceptionModel exModel = new ExceptionModel(message);
where message parameter is a relevant string like "Printer X already exists".
My thoughts were to have a partial view called ExceptionMessageView where my ExceptionModel would be passed on to it and I will display:
#Html.DisplayFor(model => model.ExceptionMessage)
And in my Index and Create views, I will have a line like:
#Html.Partial("~/Views/Home/ExceptionMessageView.cshtml")
Am I over complicating things? This isn't working anyway since I don't fully understand how to pass on the populated ExceptionModel from my Create Controller to the ExceptionMessageView partial view.
Will a kind soul please enlighten?
I would have a complex Viewmodel "PrinterViewModel" that has properties for ExceptionModel and PrinterMapping.
The controller then passes the complete PrinterViewModel to the view.
In the View you would render partials by passing part of the complex Viewmodel to them.
#Html.Partial("ExceptionMessageView",Model.Exception)
I am using Entity Framework 4.3.1, with auto-generated entities from the database.
From this, is there any way to set the default value to something? I don't want to put it in the auto-generated code since it will be overwritten.
I understand that it is possible to use partial classes, so I tried something like this, where entity is generated, and DESCRIPTION_ is the attribute I want to set to a default value.
namespace name.Models
{
public partial class ENTITY
{
public string DESCRIPTION_
{
set { _DESCRIPTION_ = "default string"; }
}
}
}
Maybe if somebody could give me an example that would be great!
The example you give means that DESCRIPTION can only ever be "default string"
You can set it in the constructor
namespace name.Models
{
public partial class ENTITY
{
private string defaultDescription = "some text";
public ENTITY() {
DESCRIPTION_ = defaultDescription;
}
}
}
or by switching your property to one with a backing field
namespace name.Models
{
public partial class ENTITY
{
private string _desc = "some default value";
public virtual string DESCRIPTION_ {get {return _desc} set {_desc = value;} }
}
}
You use OnCreated on the partial class:
public partial class ENTITY
{
partial void OnCreated()
{
DESCRIPTION_ = "default string";
}
}
I have used the Entity Framework with VS2010 to create a simple person class with properties, firstName, lastName, and email. If I want to attach DataAnnotations like as is done in this blog post I have a small problem because my person class is dynamically generated. I could edit the dynamically generated code directly but any time I have to update my model all my validation code would get wiped out.
First instinct was to create a partial class and try to attach annotations but it complains that I'm trying to redefine the property. I'm not sure if you can make property declarations in C# like function declarations in C++. If you could that might be the answer. Here's a snippet of what I tried:
namespace PersonWeb.Models
{
public partial class Person
{
[RegularExpression(#"(\w|\.)+#(\w|\.)+", ErrorMessage = "Email is invalid")]
public string Email { get; set; }
/* ERROR: The type 'Person' already contains a definition for 'Email' */
}
}
A buddy class is more or less the direction your code snippet is journeying, except your manually coded partial Person class would have an inner class, like:
[MetadataType(typeof(Person.Metadata))]
public partial class Person {
private sealed class MetaData {
[RegularExpression(...)]
public string Email { get; set; }
}
}
Or you could have your manually partial Person class and a separate Meta class like:
[MetadataType(typeof(PersonMetaData))]
public partial class Person { }
public class PersonMetaData {
[RegularExpression(...)]
public string Email;
}
These are workarounds and having a mapped Presentation class may be more suitable.
You need to either use a metadata "buddy" class or (my preference) project onto a presentation model instead of binding views directly to entities.