Home Database Mysql Tutorial [.NET] Titan ORM 中执行数据添加Insert-快速示例

[.NET] Titan ORM 中执行数据添加Insert-快速示例

Jun 07, 2016 pm 03:07 PM
.net insert orm implement data Add to

本 示例 使用SqlServer2005,先在 数据 库中创建一张表, 其中CustomerId是主键且自动增长;CustomerType用来保存int枚举,字段类型使用int;InsertTime将系统时间作为默认值 CREATE TABLE [ Customer ] ( [ CustomerId ] [ int ] IDENTITY ( 1 , 1 ) NOT NU

示例使用SqlServer2005,先在数据库中创建一张表,

其中CustomerId是主键且自动增长;CustomerType用来保存int枚举,字段类型使用int;InsertTime将系统时间作为默认值

1

2

3

4

5

6

7

8

<span>CREATE</span> <span>TABLE</span> <span>[</span><span>Customer</span><span>]</span><span>(

    </span><span>[</span><span>CustomerId</span><span>]</span> <span>[</span><span>int</span><span>]</span> <span>IDENTITY</span>(<span>1</span>,<span>1</span>) <span>NOT</span> <span>NULL</span><span>,

    </span><span>[</span><span>CustomerName</span><span>]</span> <span>[</span><span>nvarchar</span><span>]</span>(<span>50</span>) <span>NOT</span> <span>NULL</span><span>,

    </span><span>[</span><span>CustomerType</span><span>]</span> <span>[</span><span>int</span><span>]</span> <span>NOT</span> <span>NULL</span><span>,

    </span><span>[</span><span>Description</span><span>]</span> <span>[</span><span>int</span><span>]</span> <span>NULL</span><span>,

    </span><span>[</span><span>InsertTime</span><span>]</span> <span>[</span><span>datetime</span><span>]</span> <span>NOT</span> <span>NULL</span> <span>default</span>(<span>getdate</span>()), <span>--</span><span>用于测试在<strong>数据</strong>库中设置默认值</span>

    <span>CONSTRAINT</span> <span>[</span><span>PK_Customer</span><span>]</span> <span>PRIMARY</span> <span>KEY</span>(<span>[</span><span>CustomerId</span><span>]</span><span>)

) </span><span>ON</span> <span>[</span><span>PRIMARY</span><span>]</span>

Copy after login

接下来创建相应的实体类,可以使用枚举:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

<span>    public</span> <span>enum</span><span> CustomerType

    {

        Home, Abroad

    }

 

    [Table]

    </span><span>public</span> <span>class</span><span> Customer

    {

        [Column(IsPrimaryKey</span>=<span>true</span><span>)]

        [SqlServerColumn(IsIdentity</span>=<span>true</span>)]<span>//</span><span>针对SqlServer特有的标识列</span>

        <span>public</span> <span>int</span> CustomerId { <span>get</span>; <span>set</span><span>; }

 

        [Column]

        </span><span>public</span> <span>string</span> CustomerName { <span>get</span>; <span>set</span><span>; }

 

        [Column]

        </span><span>public</span> CustomerType CustomerType { <span>get</span>; <span>set</span><span>; }

 

        [Column]

        </span><span>public</span> <span>string</span> Description { <span>get</span>; <span>set</span><span>; }

 

        [Column]

        [SqlServerColumn(GenerateInsert</span>=AttributeBoolean.False)]<span>//<strong>数据</strong>库中已有默认值,</span><span>告诉Titan在生成Insert语句时不要包含本列</span>

        <span>public</span> DateTime InsertTime { <span>get</span>; <span>set</span><span>; }

    }</span>

Copy after login

使用Titan往数据库中添加一条记录:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

<span>    class</span><span> Program

    {

        </span><span>static</span> <span>void</span> Main(<span>string</span><span>[] args)

        {

            IDbSession se </span>=<span> OpenDbSession();

 

            Customer customer </span>= <span>new</span><span> Customer();

            customer.CustomerName </span>= <span>"</span><span>customer name</span><span>"</span><span>;

            customer.CustomerType </span>=<span> CustomerType.Abroad;

 

            se.Insert(customer);

            Console.WriteLine(</span><span>string</span>.Format(<span>"</span><span><strong>执行</strong>Insert后标识列返回的CustomerId={0}</span><span>"</span><span>,customer.CustomerId));

 

            se.Close();

 

            Console.ReadLine();

        }

 

        </span><span>static</span><span> IDbSession OpenDbSession()

        {

            </span><span>//</span><span>使用SqlServer。如果是其它<strong>数据</strong>库则可以使用:OracleSqlProvider,MySqlSqlProvider,SQLiteSqlProvider...</span>

            Type providerType = <span>typeof</span><span>(SqlServerSqlProvider);

 

            </span><span>//</span><span><strong>数据</strong>库连接支付串</span>

            <span>string</span> connectionString = <span>@"</span><span>Data Source=192.168.17.129\SQLEXPRESS;Initial Catalog=titandemo;User Id=sa;Password=123456;</span><span>"</span><span>;

 

            </span><span>//</span><span>sql语句追踪,可以跟踪Titan生成的Sql语句,此处使用控制台中查看生成的Sql语句</span>

            ISqlTracer[] sqlTracers = <span>new</span> ISqlTracer[] { <span>new</span><span> ConsoleSqlTracer() };

 

            </span><span>return</span><span> DbSessionFactory.CreateAndOpenSession(providerType, connectionString, sqlTracers);

        }

    }</span>

Copy after login

查看数据库已经添加成功:

控制台程序运行截屏:

从中可以看到生成的Sql语句中不包含CustomerId列和InsertTime列,

由于CustomerId使用了[SqlServerColumn(IsIdentity=true)]标注,Titan在生成Insert语句时不会包含此列,默认情况下还会在Insert语句中包含set @4=SCOPE_Identity()用以取回数据库自动生成的值。

另外数据库中InsertTime列使用了默认值,并且实体类属性中使用了[SqlServerColumn(GenerateInsert=AttributeBoolean.False)]标注,因此生成的Sql语句中也不包含此列。 

关于IsIdentity=true标注,如果在[Column]标注中强制不返回,那么Insert语句中set @4=SCOPE_Identity()语句不会被生成。代码如下(注意红色部分):

1

2

3

4

5

6

<span>    [Table]

    </span><span>public</span> <span>class</span><span> Customer

    {

        [Column(IsPrimaryKey </span>= <span>true</span>, <span>ReturnAfterInsert =</span><span><span> AttributeBoolean.False</span>)]

        [SqlServerColumn(IsIdentity </span>= <span>true</span>)]<span>//</span><span>针对SqlServer特有的标识列</span>

        <span>public</span> <span>int</span> CustomerId { <span>get</span>; <span>set</span>; }

Copy after login

再运行程序,发现Insert语句中不再包含set @4=SCOPE_Identity(),CustomerId的值仍为0。

 

 

 

 

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Open source! Beyond ZoeDepth! DepthFM: Fast and accurate monocular depth estimation! Open source! Beyond ZoeDepth! DepthFM: Fast and accurate monocular depth estimation! Apr 03, 2024 pm 12:04 PM

0.What does this article do? We propose DepthFM: a versatile and fast state-of-the-art generative monocular depth estimation model. In addition to traditional depth estimation tasks, DepthFM also demonstrates state-of-the-art capabilities in downstream tasks such as depth inpainting. DepthFM is efficient and can synthesize depth maps within a few inference steps. Let’s read about this work together ~ 1. Paper information title: DepthFM: FastMonocularDepthEstimationwithFlowMatching Author: MingGui, JohannesS.Fischer, UlrichPrestel, PingchuanMa, Dmytr

Google is ecstatic: JAX performance surpasses Pytorch and TensorFlow! It may become the fastest choice for GPU inference training Google is ecstatic: JAX performance surpasses Pytorch and TensorFlow! It may become the fastest choice for GPU inference training Apr 01, 2024 pm 07:46 PM

The performance of JAX, promoted by Google, has surpassed that of Pytorch and TensorFlow in recent benchmark tests, ranking first in 7 indicators. And the test was not done on the TPU with the best JAX performance. Although among developers, Pytorch is still more popular than Tensorflow. But in the future, perhaps more large models will be trained and run based on the JAX platform. Models Recently, the Keras team benchmarked three backends (TensorFlow, JAX, PyTorch) with the native PyTorch implementation and Keras2 with TensorFlow. First, they select a set of mainstream

Slow Cellular Data Internet Speeds on iPhone: Fixes Slow Cellular Data Internet Speeds on iPhone: Fixes May 03, 2024 pm 09:01 PM

Facing lag, slow mobile data connection on iPhone? Typically, the strength of cellular internet on your phone depends on several factors such as region, cellular network type, roaming type, etc. There are some things you can do to get a faster, more reliable cellular Internet connection. Fix 1 – Force Restart iPhone Sometimes, force restarting your device just resets a lot of things, including the cellular connection. Step 1 – Just press the volume up key once and release. Next, press the Volume Down key and release it again. Step 2 – The next part of the process is to hold the button on the right side. Let the iPhone finish restarting. Enable cellular data and check network speed. Check again Fix 2 – Change data mode While 5G offers better network speeds, it works better when the signal is weaker

How to add a TV to Mijia How to add a TV to Mijia Mar 25, 2024 pm 05:00 PM

Many users are increasingly favoring the electronic ecosystem of Xiaomi smart home interconnection in modern life. After connecting to the Mijia APP, you can easily control the connected devices with your mobile phone. However, many users still don’t know how to add Mijia to their homes. app, then this tutorial guide will bring you the specific connection methods and steps, hoping to help everyone in need. 1. After downloading Mijia APP, create or log in to Xiaomi account. 2. Adding method: After the new device is powered on, bring the phone close to the device and turn on the Xiaomi TV. Under normal circumstances, a connection prompt will pop up. Select &quot;OK&quot; to enter the device connection process. If no prompt pops up, you can also add the device manually. The method is: after entering the smart home APP, click the 1st button on the lower left

The vitality of super intelligence awakens! But with the arrival of self-updating AI, mothers no longer have to worry about data bottlenecks The vitality of super intelligence awakens! But with the arrival of self-updating AI, mothers no longer have to worry about data bottlenecks Apr 29, 2024 pm 06:55 PM

I cry to death. The world is madly building big models. The data on the Internet is not enough. It is not enough at all. The training model looks like "The Hunger Games", and AI researchers around the world are worrying about how to feed these data voracious eaters. This problem is particularly prominent in multi-modal tasks. At a time when nothing could be done, a start-up team from the Department of Renmin University of China used its own new model to become the first in China to make "model-generated data feed itself" a reality. Moreover, it is a two-pronged approach on the understanding side and the generation side. Both sides can generate high-quality, multi-modal new data and provide data feedback to the model itself. What is a model? Awaker 1.0, a large multi-modal model that just appeared on the Zhongguancun Forum. Who is the team? Sophon engine. Founded by Gao Yizhao, a doctoral student at Renmin University’s Hillhouse School of Artificial Intelligence.

Tesla robots work in factories, Musk: The degree of freedom of hands will reach 22 this year! Tesla robots work in factories, Musk: The degree of freedom of hands will reach 22 this year! May 06, 2024 pm 04:13 PM

The latest video of Tesla's robot Optimus is released, and it can already work in the factory. At normal speed, it sorts batteries (Tesla's 4680 batteries) like this: The official also released what it looks like at 20x speed - on a small "workstation", picking and picking and picking: This time it is released One of the highlights of the video is that Optimus completes this work in the factory, completely autonomously, without human intervention throughout the process. And from the perspective of Optimus, it can also pick up and place the crooked battery, focusing on automatic error correction: Regarding Optimus's hand, NVIDIA scientist Jim Fan gave a high evaluation: Optimus's hand is the world's five-fingered robot. One of the most dexterous. Its hands are not only tactile

Alibaba 7B multi-modal document understanding large model wins new SOTA Alibaba 7B multi-modal document understanding large model wins new SOTA Apr 02, 2024 am 11:31 AM

New SOTA for multimodal document understanding capabilities! Alibaba's mPLUG team released the latest open source work mPLUG-DocOwl1.5, which proposed a series of solutions to address the four major challenges of high-resolution image text recognition, general document structure understanding, instruction following, and introduction of external knowledge. Without further ado, let’s look at the effects first. One-click recognition and conversion of charts with complex structures into Markdown format: Charts of different styles are available: More detailed text recognition and positioning can also be easily handled: Detailed explanations of document understanding can also be given: You know, "Document Understanding" is currently An important scenario for the implementation of large language models. There are many products on the market to assist document reading. Some of them mainly use OCR systems for text recognition and cooperate with LLM for text processing.

The U.S. Air Force showcases its first AI fighter jet with high profile! The minister personally conducted the test drive without interfering during the whole process, and 100,000 lines of code were tested for 21 times. The U.S. Air Force showcases its first AI fighter jet with high profile! The minister personally conducted the test drive without interfering during the whole process, and 100,000 lines of code were tested for 21 times. May 07, 2024 pm 05:00 PM

Recently, the military circle has been overwhelmed by the news: US military fighter jets can now complete fully automatic air combat using AI. Yes, just recently, the US military’s AI fighter jet was made public for the first time and the mystery was unveiled. The full name of this fighter is the Variable Stability Simulator Test Aircraft (VISTA). It was personally flown by the Secretary of the US Air Force to simulate a one-on-one air battle. On May 2, U.S. Air Force Secretary Frank Kendall took off in an X-62AVISTA at Edwards Air Force Base. Note that during the one-hour flight, all flight actions were completed autonomously by AI! Kendall said - "For the past few decades, we have been thinking about the unlimited potential of autonomous air-to-air combat, but it has always seemed out of reach." However now,

See all articles