Yesterday we were doing the preparatory work , Finally, the form data needs to be extracted from the database , And save to database , Today, I'm going to talk about how to extract 、 Preservation and validation .

Four 、 Extract and display information

stay EditForm Let's define a InfoId attribute , Used to receive the primary key when the edit form is opened on the list page , Then edit the form and query the entity through the primary key , Finally fill in the mapped control .

 /// <summary>
/// Get or set information ID, According to this ID Query entities and fill in the form .
/// </summary>
public string InfoId { get; set; }

On the window Load Incident , Judge InfoId Is it empty , If it is not empty, the entity object will be found , Fill the data into the controls .

 private void EditForm_Load(object sender, EventArgs e)
{
if (!DesignMode)
{
LoadInfo();
}
} /// <summary>
/// Read entity information , On the form .
/// </summary>
protected virtual void LoadInfo()
{
if (EntityType == null || EntityPropertyExtend == null)
{
Helper.ShowError(" No binding EntityType or EntityPropertyExtend.");
return;
} if (!string.IsNullOrEmpty(InfoId))
{
using (var persister = new EntityPersister(EntityType))
{
var entity = persister.First(InfoId) as IEntity;
if (entity == null)
{
return;
} FillEntityValues(entity);
}
}
} /// <summary>
/// Fill the form with the property values of the entity .
/// </summary>
/// <param name="entity"></param>
protected virtual void FillEntityValues(IEntity entity)
{
foreach (var kvp in EntityPropertyExtend.GetProperties())
{
var value = entity.GetValue(kvp.Value);
if (value == null || value.IsEmpty)
{
continue;
} var converter = ControlEntityMapHelper.GetMapper(kvp.Key.GetType()); if (converter != null)
{
converter.SetValue(kvp.Key, value.GetStorageValue());
}
}
}

5、 ... and 、 Data validation and preservation

Fireasy.Data.Entity be based on System.ComponentModel.DataAnnotations The internal verification mechanism is implemented . In persistent objects Create and Update Before , Would call ValidationUnity Validate entity objects .

On the form , We still use ErrorProvider Component to display the verification prompt .

 private void btnSave_Click(object sender, EventArgs e)
{
SaveData();
} /// <summary>
/// Save form data to database .
/// </summary>
/// <param name="createNew"> Whether to create new information after saving .</param>
/// <returns></returns>
protected virtual IEntity SaveData(bool createNew = false)
{
if (EntityType == null || EntityPropertyExtend == null)
{
Helper.ShowError(" No binding EntityType or EntityPropertyExtend.");
return null;
} // Clean up the verification error prompt
errorProvider1.Clear(); try
{
using (var persister = new EntityPersister(EntityType))
{
var entity = (string.IsNullOrEmpty(InfoId) ? persister.NewEntity() : persister.First(InfoId)) as IEntity;
if (entity == null)
{
return null;
} ReadEntityValues(entity); var infoId = string.Empty;
if (entity.EntityState == EntityState.Attached)
{
infoId = SetPrimaryProperty(entity);
} persister.Save(entity); if (entity.EntityState == EntityState.Attached)
{
InfoId = infoId;
} Helper.ShowInformation(" Data saved successfully .");
return entity;
}
}
catch (EntityInvalidateException exp)
{
ShowPropertyInvalidateMessages(exp);
}
catch (Exception exp)
{
var log = LoggerFactory.CreateLogger();
if (log != null)
{
log.Error("[" + EntityType + "] Failed to save data ", exp);
} Helper.ShowError(" Data save failure .", exp);
} return null;
}

ReadEntityValues Method is used to read data from a form control , And then write it to the entity object .

 /// <summary>
/// Read control values on the window , Write to entity properties .
/// </summary>
/// <param name="entity"></param>
protected virtual void ReadEntityValues(IEntity entity)
{
foreach (var kvp in EntityPropertyExtend.GetProperties())
{
var converter = ControlEntityMapHelper.GetMapper(kvp.Key.GetType()); if (converter != null)
{
var value = converter.GetValue(kvp.Key);
var property = PropertyUnity.GetProperty(EntityType, kvp.Value);
entity.SetValue(kvp.Value, PropertyValue.New(value, property.Type));
}
}
}

PropertyValue yes Fireasy.Data.Entity Class in , You can refer to Fireasy.Data.Entity Components .
    SetPrimaryProperty The value used to manually set the primary key .

 /// <summary>
/// Set the value of the primary key , And return the primary key property .
/// </summary>
/// <param name="entity"></param>
/// <returns></returns>
private string SetPrimaryProperty(IEntity entity)
{
var keyValue = Guid.NewGuid().ToString("N");
var accessor = entity as IEntityPropertyAccessor;
var pk = PropertyUnity.GetPrimaryProperties(EntityType).FirstOrDefault();
accessor.SetValue(pk, keyValue);
return keyValue;
}

If entity validation fails , Will throw out a EntityInvalidateException Exception information for type , This object includes the attributes of failed verification and the corresponding error information , And global validation features defined on entity types , That is, not a single attribute value validation , It's business logic validation .

 /// <summary>
/// Displays the message that the validation failed .
/// </summary>
/// <param name="exp"></param>
private void ShowPropertyInvalidateMessages(EntityInvalidateException exp)
{
var sb = new StringBuilder();
foreach (var property in exp.PropertyErrors)
{
// Find if there is a control associated with a validation failure property
var map = EntityPropertyExtend.GetProperties().Where(s => s.Value == property.Key.Name).FirstOrDefault();
if (map.Key == null)
{
sb.AppendLine(string.Join("\n", property.Value.ToArray()));
continue;
} // Displays information about validation failures on the control
errorProvider1.SetError(map.Key, string.Join("\n", property.Value.ToArray()));
} if (sb.Length > )
{
Helper.ShowError(" The data is incomplete , It also includes the following information :\n" + sb.ToString());
}
}

6、 ... and 、 Operation example

Run the program , Look at what we defined earlier ProductEdit forms .

We double-click a piece of data from the list to edit it ,Book The relevant data is automatically filled into the control .

Let's clear individual texts , Or enter a long string , The save will fail , And display the red icon on the form .

7、 ... and 、 Verify the definition of the class

Last , take Book The verification class of , In order to be more intuitive .

 // If you want to enable entity validation , Use the following features , And in BookMetadata Validation features are defined in .
[MetadataType(typeof(BookMetadata))]
public partial class Book
{
} public class BookMetadata
{ /// <summary>
/// attribute Id Verification characteristics of .
/// </summary> [Required]
[StringLength()]
public object Id { get; set; } /// <summary>
/// attribute ISBN Verification characteristics of .
/// </summary> [StringLength()]
public object ISBN { get; set; } /// <summary>
/// attribute BarCode Verification characteristics of .
/// </summary> [Required]
[StringLength()]
public object BarCode { get; set; } /// <summary>
/// attribute PyCode Verification characteristics of .
/// </summary> [StringLength()]
public object PyCode { get; set; } /// <summary>
/// attribute Name Verification characteristics of .
/// </summary> [Required]
[StringLength()]
public object Name { get; set; } /// <summary>
/// attribute Price Verification characteristics of .
/// </summary> [Required]
public object Price { get; set; } /// <summary>
/// attribute Agio Verification characteristics of .
/// </summary> [Required]
public object Agio { get; set; } /// <summary>
/// attribute Unit Verification characteristics of .
/// </summary> [Required]
[StringLength()]
public object Unit { get; set; } /// <summary>
/// attribute SizeNo Verification characteristics of .
/// </summary> [StringLength()]
public object SizeNo { get; set; } /// <summary>
/// attribute MediaNo Verification characteristics of .
/// </summary> [StringLength()]
public object MediaNo { get; set; } /// <summary>
/// attribute VolumesOfBar Verification characteristics of .
/// </summary> public object VolumesOfBar { get; set; } /// <summary>
/// attribute BarsOfBag Verification characteristics of .
/// </summary> public object BarsOfBag { get; set; } /// <summary>
/// attribute Emphasis Verification characteristics of .
/// </summary> public object Emphasis { get; set; } /// <summary>
/// attribute TypeCode Verification characteristics of .
/// </summary> [StringLength()]
public object TypeCode { get; set; } /// <summary>
/// attribute PublisherId Verification characteristics of .
/// </summary> [StringLength()]
public object PublisherId { get; set; } /// <summary>
/// attribute PublishDate Verification characteristics of .
/// </summary> public object PublishDate { get; set; } /// <summary>
/// attribute UpperLimit Verification characteristics of .
/// </summary> [Required]
public object UpperLimit { get; set; } /// <summary>
/// attribute LowerLimit Verification characteristics of .
/// </summary> [Required]
public object LowerLimit { get; set; } /// <summary>
/// attribute State Verification characteristics of .
/// </summary> public object State { get; set; } /// <summary>
/// attribute Remark Verification characteristics of .
/// </summary> [StringLength()]
public object Remark { get; set; } /// <summary>
/// attribute MarkColor Verification characteristics of .
/// </summary> [StringLength()]
public object MarkColor { get; set; } /// <summary>
/// attribute DelFlag Verification characteristics of .
/// </summary> public object DelFlag { get; set; } }

Winform Rapid development of component implementation ( Two ) More articles about

  1. Winform Rapid development of component implementation ( One )

    I haven't shown up for a long time , ha-ha , I'm a little unfamiliar with writing articles . After getting any project , Whether it's b/s or c/s, I'm not going to start writing code right away , I usually develop a series of support components to enable these projects to develop rapidly , Although there may be some early costs ...

  2. winform Rapid development platform -&gt; Workflow components ( Imitation GooFlow)

    about web Direction workflow , Have been using gooflow For the moment, my winform The development platform has no better workflow components .   For the current project experience tells us . A workflow control is necessary . Of course. winform The workflow of aspect 3 ...

  3. winform Rapid development platform -&gt; Basic components of the paging control

    A project control is mainly composed of some common components , Of course, this is a general paging control . Dealing with ideas : We deal with paging mainly for database operation . In general, it is mainly to transfer some starting positions , The current number of pages , And the total number of pages of data and related business logic . ...

  4. winform Rapid development platform -&gt; Let limited resources create unlimited value !

    Recently, I have been maintaining my own rapid development platform . The main response is C/S Projects under the framework . However, yes. winform This is fast , I really haven't seen a relatively good rapid development platform , What is fast , I've been in the blog Garden for a long time , Preview a lot of common rights management systems . indeed ...

  5. winform Rapid development platform -&gt; Dynamic menu of general authority management

    I've been busy for months APP Project , No time to update the project , Think about taking the time to sort out development ideas , Share with you , At the same time, I hope to get valuable suggestions . Let's talk about the design idea of our authority management first , First of all, an enterprise information management system must use authority management , ...

  6. winform Rapid development platform -&gt; Fast binding ComboBox Data controls

    Usually when we're dealing with editing forms . Data binding is often encountered . for example combobox Control binding data dictionary may be something we often use . But in my winform How do I deal with this frequent operation in the rapid development platform ? First , We're going to bind combo ...

  7. BOLT.NET Learning notes ( One ) The opening use .net winform Rapid development of Cool interface

    BOLT.NET Learning notes ( One ) The opening use .net winform Rapid development of Cool interface bolt Basic introduction Bolt The interface engine is from thunderbolt 2009 The fourth generation of interface library started to develop in . thunderbolt 7 It's the first one to use this engine successfully ...

  8. C#.NET Winform Rapid development platform

    C/S System development framework - Enterprise Edition V4.0 (Enterprise Edition) brief introduction : http://www.csframework.com/cs-framework-4.0.htm Applicable software : Suitable for ...

  9. SNF Development platform WinForm Twelve - Send SMS function call - Golden flute -SNF Rapid development platform 3.3-Spring.Net.Framework

    1. Assemble parameters before calling 2. Call the send information service script   . Assemble parameters before calling : BaseSendTaskEntity entity = new BaseSendTaskEntity(); entity.Mess ...

Random recommendation

  1. Use openfiler Set up SMB/CIFS Sharing is always an example and solution of not passing

    Recently used openfiler Centralized management of idle storage and sharing with multi host nodes , When it's set to SMB/CIFS I always can't get through when I'm on the road , The premise needs to be opened LDAP Built in openfiler It's all turned on and set up , But it just can't pass &qu ...

  2. Javascript Secondary linkage

    Mainly used to address JSON Format , To do it , There is no database read involved . <!DOCTYPE html><html><head> <meta charset=" ...

  3. Aspose.Words summary

    Generate answer sheets try { string tempPath = @"D:\moban\ttt.doc"; //Open document and create Documentbuil ...

  4. Bootstrap-- Button group of components

    What is a button group ? Simple explanation : It's just putting a bunch of buttons in a row or a column . Here's an example . Button group , First, the buttons , So it uses .btn This class , And that is bootstrap Button groups provided .btn-group This class , therefore ...

  5. Two points -poj-3685-Matrix

    Topic link : http://poj.org/problem?id=3685 The main idea of the topic : Yes n*n Matrix , The first i Xing di j The number of columns is Aij= i2 + 100000 × i + j2 - 100000 × j + ...

  6. How to use jQuery Achieve five-star praise

    jQuery yes js A library , It encapsulates some common functions in our development process , It's convenient for us to call , Improve our development efficiency . Js The library is to put our common functions into a single file , When we use it , Just refer to the page directly . continue with ...

  7. Linux Programming 11(shell Global environment variable and local environment variable )

    One . summary stay linux in , Many programs and scripts get system information through environment variables , Store temporary data , Configuration information . Environment variables are used to store information about shell Conversation and work environment information , Allows you to store data in memory , So that the program or shell Running in ...

  8. CRM INBOX Results enhanced function

    The demand received some time ago :INBOX(ICCMP_INBOX) Query results , After multiple selection, the user selection box will pop up , Select the user , Brought into the document PARTNER FUNC Among the engineers in China , And modify the document status . In fact, the standard INBOX Of Compon ...

  9. redis The use of game server ( One ) Environment building

    Here we try to use in the data processing of the game server redis Through this series of articles, we can learn redis Basic operation Source code compilation Compilation and use of client open source library And the use of cache in the game server For the first time   Try to make the environment as simple as possible   ...

  10. Operating firewalls -centos7

    centos7 The operation of firewall systemctl status firewalld # View firewall status systemctl stop firewalld.service # Stop firewall systemctl ...