Главная » Съедобные грибы » Анемия – English page. Несколько слов в защиту шаблона "Анемичная модель предметной области" (Anemic Domain Model)

Анемия – English page. Несколько слов в защиту шаблона "Анемичная модель предметной области" (Anemic Domain Model)

Причиной повышенной утомляемости, сонливости, шума в ушах не во всех случаях выступают напряженный режим работы и интенсивный ритм жизни. Если человек испытывает такое и пока не знает, что такое анемия (с лат. anaemia), необходимо обратиться за консультацией к врачу. Под этим термином подразумевают состояние, при котором в организме есть дефицит эритроцитов, выполняющих функцию по переносу кислорода к тканям. Вовремя обратившись за медицинской помощью, можно предотвратить развитие тяжелых форм патологии.

Значение понятия

Гемоглобин является основной частью эритроцитов. В его составе есть ион железа, связывающий кислород. При недостатке красных кровяных тел в организме постепенно наступает аноксия (гипоксия). Симптомами анемии в этом случае выступают усталость, головные боли, одышка. Малокровию по международной классификации болезней присвоен код МКБ-10, согласно данным Минздрава РФ у 15% населения выявляется эта патология. Наиболее подвержены ей беременные (40%), на следующем месте в группе риска находятся дети до 2 лет (18-25%).

В медицине выделяют несколько видов этого клинико-гематологического синдрома, которые могут быть врожденными или приобретенными. Научно доказано, что молодые женщины чувствительны к дефициту эритроцитов, поскольку во время менструального цикла происходит большая потеря крови. У людей пожилого возраста болезнь анемия развивается из-за плохого питания и на фоне хронических заболеваний. Таким образом, малокровие выступает в качестве вторичного симптома имеющихся нарушений в организме.

Некоторые формы болезни, появляющиеся во время беременности, считаются нормальными, но нужно знать, чем опасна анемия для пациентов различных возрастных групп. При длительно протекающей гипоксии нарушаются внутренние обменные процессы, скапливаются токсические продукты, развивается дисфункция почек и печени, сердца, легких. Пациент может долгое время не замечать наличия болезни, которая постепенно перерастет в хроническую форму. В конечном итоге появляются жалобы на одышку, отеки рук и ног, учащенное сердцебиение, снижение работоспособности. До прохождения лабораторных анализов врачи подразумевают наличие анемии неясного патогенеза.

Этиология заболевания

Малокровие диагностируется у пациентов на фоне выявления различных факторов. Известны следующие основные причины анемии:

  1. Потеря большого объема крови при тяжелом менструальном цикле, глубоких ранах, на фоне злокачественного рака толстой кишки, кишечных язв.
  2. Дисфункция почек, при которой снижается производство в костном мозгу эритропоэтина, вырабатывающего ретикулоциты (предшественники эритроциты).
  3. Заболевание может передаться по наследству от родственников первой линии.
  4. Нерациональное питание, дефицит витаминов группы В12 и С, фолиевой кислоты, железа.
  5. Анемия развивается на фоне хронических патологий: болезнь Крона, СПИД, ВИЧ, ревматоидный артрит, карцинома.
  6. Проявление признаков поражения кроветворной системы связано и с психосоматикой. Анемия выступает в качестве специфического сигнала организма о том, что человек излишне самокритичен, недоволен своей жизнью. В этом случае психологи рекомендуют мысленно повторять про себя, что новый путь и мысли не несут угрозы и совершенно безопасны.
  7. Организм некоторых людей не способен усваивать витамин В12, что приводит к развитию малокровия. Уменьшение всасывания полезных веществ могут обусловить молочные продукты, твердая пища, злаки в сыром виде.
  8. При отсутствии заболеваний эритроциты живут 100 дней. При поражении селезенки развивается гемолиз, при котором нарушается их функционирование.
  9. Этанол токсичен для мозговой деятельности и замедляет продукцию эритроцитов. При сочетании этих факторов у хронических алкоголиков существенно повышаются риски развития анемии.
  10. Истощение внутренних резервов железа провоцируется чаще всего у женщин, борющихся с лишним весом и придерживающихся строгих диет.
  11. Анемия нередко проявляется в предоперационном периоде. Поэтому хирург должен оценить в полной мере риск вмешательства и повысить уровень гемоглобина до нормы, чтоб снизить нагрузку на сердечно-сосудистую систему.

Анемия - English page

Anemia

This web site presents patients" information regarding different types of anemia. It was created in Russia by hematologists - doctors who are dealing with blood diseases
If you have any questions regarding this resource please contact us through e-mail or by phone (+7-495-741-06-41)

If you have anemia, people may say you have tired blood. That"s because anemia — a condition in which there aren"t enough healthy red blood cells to carry adequate oxygen to your tissues — can make you feel tired.

There are many forms of anemia, each with its own cause. Anemia can be temporary or long term, and it can range from mild to severe.

Anemia is a common blood disorder. Women and people with chronic diseases are at increased risk of the condition.

If you suspect you have anemia, see your doctor. Anemia can be a sign of serious illnesses. Treatments for anemia range from taking supplements to undergoing medical procedures. You may be able to prevent some types of anemia by eating a healthy, varied diet.

Symptoms

The main symptom of most types of anemia is fatigue. Other anemia symptoms include:

  • Weakness
  • Pale skin
  • A fast or irregular heartbeat
  • Shortness of breath
  • Chest pain
  • Dizziness
  • Cognitive problems
  • Numbness or coldness in your extremities
  • Headache

Initially, anemia can be so mild it goes unnoticed. But signs and symptoms increase as the condition worsens.

Causes

Blood consists of both a liquid called plasma and cells. Floating within the plasma are three types of blood cells:

  • White blood cells. These blood cells fight infection.
  • Platelets. These blood cells help your blood clot after a cut.
  • Red blood cells (erythrocytes). These blood cells carry oxygen from your lungs, via your bloodstream, to your brain and the other organs and tissues. Your body needs a supply of oxygenated blood to function. Oxygenated blood helps give your body its energy and your skin a healthy glow.

Red blood cells contain hemoglobin — a red, iron-rich protein that gives blood its red color. Hemoglobin enables red blood cells to carry oxygen from your lungs to all parts of your body, and to carry carbon dioxide from other parts of the body to the lungs so that it can be exhaled.

Most blood cells, including red blood cells, are produced regularly in your bone marrow — a red, spongy material found within the cavities of many of your large bones. To produce hemoglobin and red blood cells, your body needs iron, protein and vitamins from the foods you eat.

Anemia is a state in which the number of red blood cells or the hemoglobin in them is below normal. When you"re anemic, your body produces too few healthy red blood cells, loses too many of them or destroys them faster than they can be replaced. As a result, your blood is low on red blood cells to carry oxygen to your tissues — leaving you fatigued. Common types of anemia and their causes include:

    Iron deficiency anemia. This most common form of anemia affects about one in five women, half of pregnant women and 3 percent of men in the United States. The cause is a shortage of the element iron in your body. Your bone marrow needs iron to make hemoglobin. Without adequate iron, your body can"t produce enough hemoglobin for red blood cells. The result is iron deficiency anemia.

    One way your body gets needed iron is when blood cells die — the iron in them is recycled and used to produce new blood cells. So, if you lose blood, you lose iron. Women with heavy periods who lose a lot of blood each month during menstruation are at risk of iron deficiency anemia. Slow, chronic blood loss from a source within the body — such as an ulcer, a colon polyp or even colon cancer — also can lead to iron loss and iron deficiency anemia.

    Your body also gets iron from the foods you eat. An iron-poor diet can lead to this anemia. In pregnant women, a growing fetus can deplete the mother"s store of iron, leading to iron deficiency anemia.

  • Vitamin deficiency anemias. In addition to iron, your body needs folate and vitamin B-12 to produce sufficient numbers of healthy red blood cells. A diet lacking in these and other key nutrients can cause decreased red blood cell production. People who have an intestinal disorder that affects the absorption of nutrients are prone to this type of anemia. Some people are unable to absorb vitamin B-12 for a variety of reasons and develop vitamin B-12 deficiency anemia, which is sometimes called pernicious anemia. Vitamin deficiency anemias fall into a group of anemias called megaloblastic anemias, in which the bone marrow produces large, abnormal red blood cells.
  • Anemia of chronic disease. Certain chronic diseases — such as cancer, rheumatoid arthritis, Crohn"s disease and other chronic inflammatory diseases — can interfere with the production of red blood cells, resulting in chronic anemia. Kidney failure also can be a cause of anemia. The kidneys produce a hormone called erythropoietin, which stimulates your bone marrow to produce red blood cells. A shortage of erythropoietin, which can result from kidney failure or be a side effect of chemotherapy, can result in a shortage of red blood cells.
  • Aplastic anemia. This is a life-threatening anemia caused by a decrease in the bone marrow"s ability to produce all three types of blood cells — red blood cells, white blood cells and platelets. Many times, the cause of aplastic anemia is unknown, but it"s believed to often be an autoimmune disease. Some factors that can be responsible for this type of anemia include chemotherapy, radiation therapy, environmental toxins, pregnancy and lupus.
  • A variety of diseases, such as leukemia and myelodysplasia, a pre-leukemic condition, can cause anemia by affecting blood production in the bone marrow. The effects of these types of cancer and cancer-like disorders vary from a mild alteration in blood production to a complete, life-threatening shutdown of the blood-making process. Additionally, other cancers of the blood or bone marrow, such as multiple myeloma, myeloproliferative disorders and lymphoma, can cause anemia.
  • Hemolytic anemias. This group of anemias develops when red blood cells are destroyed faster than bone marrow can replace them. Certain blood diseases can cause increased red blood cell destruction. Autoimmune disorders can cause your body to produce antibodies to red blood cells, destroying them prematurely. Certain medications, such as some antibiotics used to treat infections, also can break down red blood cells. Hemolytic anemias may cause yellowing of the skin (jaundice) and an enlarged spleen.
  • Sickle cell anemia. This inherited and sometimes serious anemia, which affects mainly people of African and Arabic descent, is caused by a defective form of hemoglobin that forces red blood cells to assume an abnormal crescent (sickle) shape. These irregular-shaped red blood cells die prematurely, resulting in a chronic shortage of red blood cells. Sickle-shaped red blood cells can also block blood flow through small blood vessels in the body, producing other, often painful, symptoms.
  • Other anemias. There are several other, rarer forms of anemia, such as thalassemia and anemias caused by defective hemoglobin.

Sometimes, no cause of anemia can be identified.

Risk factors

These factors place you at increased risk of anemia:

  • Poor diet. Anyone — young or old — whose diet is consistently low in iron and vitamins, especially folate, is at risk of anemia. Your body needs iron, protein and vitamins to produce sufficient numbers of red blood cells.
  • Intestinal disorders. Having an intestinal disorder that affects the absorption of nutrients in the small intestine — such as Crohn"s disease and celiac disease — puts you at risk of anemia. Surgical removal of or surgery to the parts of the small intestine where nutrients are absorbed can lead to nutrient deficiencies and anemia.
  • Menstruation. In general, women are at greater risk of iron deficiency anemia than are men. That"s because women lose blood — and with it, iron — each month during menstruation.
  • Pregnancy. Pregnant women are at an increased risk of iron deficiency anemia because their iron stores have to serve the increased blood volume of the mother as well as be a source of hemoglobin for the growing fetus.
  • Chronic conditions. For example, if you have cancer, kidney or liver failure, or another chronic condition, you may be at risk of what"s called anemia of chronic disease. These conditions can lead to a shortage of red blood cells. Slow, chronic blood loss from an ulcer or other source within the body can deplete your body"s store of iron, leading to iron deficiency anemia.
  • Family history. If your family has a history of an inherited anemia, you also may be at increased risk of the condition.

Certain infections, blood diseases and autoimmune disorders, exposure to toxic chemicals, and the use of some medications can affect red blood cell production and lead to anemia. Other people at risk of anemia are people with diabetes, people who are dependent on alcohol (alcohol interferes with the absorption of folic acid) and people who adhere to a strict vegetarian diet, who may not get enough iron or vitamin B-12 in their diet.

When to seek medical advice

See your doctor if you"re feeling fatigued for unexplained reasons, especially if you"re at risk of anemia. Some anemias, such as iron deficiency anemia, are common. But don"t assume that if you"re tired, you must be anemic. Fatigue has many causes besides anemia.

Some people learn that their hemoglobin is low, which indicates anemia, when they go to donate blood. Low hemoglobin may be a temporary problem remedied by eating more iron-rich foods or taking a multivitamin containing iron. However, it may also be a warning sign of blood loss in your body that may be causing you to be deficient in iron. If you"re told that you can"t donate blood because of low hemoglobin, ask your doctor if you should be concerned.

If you have a family history of an inherited anemia, such as sickle cell anemia, talk to your doctor and possibly a genetic counselor about your risk and what risks you may pass on to your children.

Tests and diagnosis

Doctors diagnose anemia with the help of a medical history, a physical exam and blood tests, including a complete blood count (CBC). This blood test measures levels of red blood cells and hemoglobin in your blood. Some of your blood may also be examined under a microscope to study the size, shape and color of your red blood cells, which may indicate a diagnosis. For example, in iron deficiency anemia, red blood cells are smaller and paler in color than normal. In vitamin deficiency anemias, red blood cells are enlarged and fewer in number.

If you receive a diagnosis of anemia, your doctor may order additional tests to determine the underlying cause. For example, iron deficiency anemia can result from chronic bleeding of known or unknown ulcers, benign polyps in the colon, colon cancer, tumors, or kidney failure. Your doctor may test for these and other conditions that may underlie the anemia.

Occasionally, it may be necessary to study a sample of your bone marrow to diagnose anemia.

Complications

When anemia is severe enough, it may interfere with your ability to do everyday tasks. You may be too exhausted to work or play. Although anemia is often treatable, it may take several weeks to months for red blood cell levels to return to normal after treatment. Ask your doctor what to expect from treatment.

If you"ve been diagnosed with anemia — it"s often detected during routine blood tests — ask your doctor what treatment is necessary. Then be sure to follow through on treatment, even if you quickly start to feel better. Left unchecked, anemia can lead to a rapid or irregular heartbeat — an arrhythmia. Your heart must pump more blood to compensate for the lack of oxygen in the blood when you"re anemic. This can even lead to congestive heart failure. Untreated pernicious anemia can lead to nerve damage and decreased mental function, as vitamin B-12 is important not only for healthy red blood cells but also for optimal nerve and brain function.

Some inherited anemias, such as sickle cell anemia, can be serious and lead to life-threatening complications. Losing a lot of blood quickly results in acute, severe anemia and can be fatal.

Treatments and drugs

Anemia treatment depends on the cause:

  • Iron deficiency anemia. This form of anemia is treated with iron supplements, which you may need to take for several months or longer. If the underlying cause of iron deficiency is loss of blood — other than from menstruation — the source of the bleeding must be located and stopped. This may involve surgery.
  • Vitamin deficiency anemias. Pernicious anemia is treated with injections — often lifetime injections — of vitamin B-12. Folic acid deficiency anemia is treated with folic acid supplements.
  • Anemia of chronic disease. There"s no specific treatment for this type of anemia. Doctors focus on treating the underlying disease. Iron supplements and vitamins generally don"t help this type of anemia. However, if symptoms become severe, a blood transfusion or injections of synthetic erythropoietin, a hormone normally produced by the kidneys, may help stimulate red blood cell production and ease fatigue.
  • Aplastic anemia. Treatment for this serious anemia may include blood transfusions to boost levels of red blood cells. You may need a bone marrow transplant if your bone marrow is diseased and can"t make healthy blood cells. You may need immune-suppressing medications to lessen your immune system"s response and give the transplanted bone marrow a chance to start functioning again.
  • Anemias associated with bone marrow disease. Treatment of these various diseases can range from simple medication to chemotherapy to bone marrow transplantation. Treatment of these types of anemia usually involves a consultation from a blood specialist (hematologist).
  • Hemolytic anemias. Managing hemolytic anemias includes avoiding suspect medications, treating related infections and taking drugs that suppress your immune system, which may be attacking your red blood cells. Short courses of treatment with steroids or gamma globulin can help suppress your immune system"s attack on your red blood cells. If the condition has caused an enlarged spleen, you may need to have your spleen removed. The spleen — a small organ below your rib cage on the left side — filters out and stores defective red blood cells. Certain hemolytic anemias can cause the spleen to become enlarged with damaged red blood cells.
  • Sickle cell anemia. Treatment for this incurable anemia may include the administration of oxygen, pain-relieving drugs, and oral and intravenous fluids to reduce pain and prevent complications. Doctors also commonly use blood transfusions, folic acid supplements and antibiotics. A bone marrow transplant may be an effective treatment in some circumstances. A cancer drug called hydroxyurea (Droxia, Hydrea) also is used to treat sickle cell anemia in adults.

Prevention

Many types of anemia can"t be prevented. However, you can help avoid iron deficiency anemia and vitamin deficiency anemias by eating a healthy, varied diet that includes foods rich in iron, folate and vitamin B-12.

The best sources of iron are beef and other meats. Other foods rich in iron include beans, lentils, iron-fortified cereals, dark green leafy vegetables, dried fruit, nuts and seeds. Folate, and its synthetic form, folic acid, can be found in citrus juices and fruits, dark green leafy vegetables, legumes and fortified breakfast cereals. Vitamin B-12 is plentiful in meat and dairy products. Foods containing vitamin C, such as citrus fruits, help increase iron absorption.

Eating plenty of iron-containing foods is particularly important for people who have high iron requirements, such as children — iron is needed during growth spurts — and pregnant and menstruating women. Adequate iron intake is also crucial for infants, strict vegetarians and long-distance runners.

Doctors may prescribe iron supplements or multivitamins containing iron for people with high iron requirements. But iron supplements are appropriate only when you need more iron than a balanced diet can provide. Don"t assume that if you"re tired that you simply need to take iron supplements. Overloading your body with iron can be dangerous.

Information from mayoclinic was used in preparation of this page

Анемия как патологическое состояние крови
Анемии представляют собой обширную группу патологических состояний и заболеваний, для которых общим признаком является снижение способности крови переносить кислород. В результате развивается гипоксия, ее гемическая форма, которая обусловливает основные клинические проявления и расстройства жизнедеятельности у больных анемией .

В медицинской литературе можно встретить одновременно разные определения понятия анемии . Если в более ранних дефинициях анемии акцент делался на уменьшении эритроцитарной массы, то сейчас этот акцент сместился на снижении содержания гемоглобина. Это связано с наличием анемии , при которой общее содержание эритроцитов в единице объема крови может не меняться. Таковой является железодефицитная анемия .

Итак, в настоящее время под анемией принято понимать состояние, характеризующееся снижением содержания гемоглобина в единице объема крови. При этом в большинстве случаев имеет место также уменьшение количества эритроцитов и их качественные (морфологические) изменения.

Классификация анемий
Классификация анемий проводится по ряду показателей.

1). По механизму развития:

1) анемии вследствие кровопотерь (постгеморрагические);

2) анемии вследствие усиленного кроверазрушения (гемолитические);

3) анемии вследствие нарушенного кровообразования, которые в свою очередь делятся на:

а) железодефицитные;

б) порфиринодефицитные;

в) В12 фолиево-дефицитные;

г) гипо-, апластические и метапластические.

2). По типу кроветворения:

1) нормобластические;

2) мегалобластические.

3). По цветовому показателю, важнейшему дифференциально-диагностическому критерию:

1) нормохромные, когда цветовой показатель равен 0,82-1,05;

2) гипохромные, если цветовой показатель меньше 0,82;

3) гиперхромные, когда цветовой показатель выше 1, 05.

К нормохромным анемиям относятся острая постгеморрагическая анемия в стадии гидремической компенсации, некоторые формы гемолитической анемии , особенно приобретенные. Гипо- и апластические анемии , как правило, являются нормохромными.

К гипохромным анемиям относятся острая постгеморрагическая анемия в стадии костно-мозговой компенсации, железодефицитные, порфириндефицитные анемии, большая часть гемолитических анемий.

Снижение цветового показателя является результатом либо уменьшения среднего размера эритроцитов, либо недостаточного их насыщения гемоглобином в связи с нарушением синтеза последнего. Причиной гипохромии может быть также периферический ретикулоцитоз, так как на стадии ретикулоцита синтез гемоглобина еще не завершен. Его синтез и накопление в ретикулоцитах продолжается до полного их созревания, поэтому регенераторные и гиперрегенераторные анемии , сопровождающиеся увеличением количества ретикулоцитов, бывают гипохромными.

Повышение цветового показателя возникает в тех случаях, когда увеличивается средний диаметр эритроцитов. Особенно резкое увеличение размеров красных кровяных клеток имеет место при мегалобластическом типе эритропоэза. Вот почему В12-фолиево-дефицитные анемии являются гиперхромными.

4). По размеру эритроцитов:

1) нормоцитарные (с нормальным средним диаметром эритроцитов 7,2-8,0 мк);

2) микроцитарные (средний диаметр эритроцитов ниже 7,2 мк);

3) макроцитарные (диаметр эритроцитов более 8 мк).

В группу макроцитарных анемий входят и мегалоцитарные анемии , при которых средний диаметр эритроцитов превышает 9,0 мкм.

К числу нормоцитарных анемий относятся острая постгеморрагическая анемия , ранняя форма железодефицитной анемии . Гипо- и апластическая анемия , как правило, является нормоцитарной, но она может быть и макроцитарной.

Микроцитарными анемиями являются железодефицитная, порфириндефицитная анемии , талассемия, микросфероцитарная болезнь Миньковского - Шоффара.

Макроцитарные анемии делятся на мегалобластные и немегалобластные, Мегалобластными макроцитарными анемиями являются В12-фолиево-дефицитная анемия , анемия после длительного употребления лекарственных препаратов, нарушающих синтез ДНК. К немегалобластным макроцитарным анемиям относятся анемии, сочетающиеся с болезнями печени, гипотиреозом. Макроцитарный характер могут приобретать аутоиммунная гемолитическая анемия , ночная пароксизмальная гемолобинурия, гемолитические анемии после криза, апластические анемии, анемии при опухолях желудочно-кишечного тракта и кроветворной системы, нередко на фоне лечения цитостатическими препаратами.

5) По регенераторной активности костного мозга, определяемой на основании содержания ретикулоцитов в периферической крови, выделяют анемии :

1) регенераторные, с достаточной функцией костного мозга. Число ретикулоцитов в периферической крови в пределах 1,0-5,0 %;

2) гипорегенераторные, с пониженной регенераторной функцией костного мозга. Количество ретикулоцитов в периферической крови меньше 0,2 %;

3) гиперрегенераторные, с повышенной регенераторной функцией костного мозга. Количество ретикулоцитов в периферической крови превышает 5,0 %;

4) арегенераторные, с резким угнетением эритропоэза. Ретикулоциты в периферической крови, как правило, не определяются.

Последнее обновление: 19.07.2016

Одним из ключевых компонентов паттерна MVC являются модели . Ключевая задача моделей - описание структуры и логики используемых данных.

Как правило, все используемые сущности в приложении выделяются в отдельные модели, которые и описывают структуру каждой сущности. В зависимости от задач и предметной области мы можем выделить различное количество моделей в приложении.

Все модели оформляются как обычные POCO-классы (plain-old CRL objects), то есть обычные классы на языке C#. Например, если мы работаем с приложением интернет-магазина мобильных телефонов, то мы могли бы определить в проекте следующую модель, представляющую телефон:

Public class Phone { public int Id { get; set; } public string Name { get; set; } public string Company { get; set; } public int Price { get; set; } }

Модель Phone определяет ряд свойств: уникальный идентификатор Id, название, компанию производителя и цену. Это классическая анемичная модель . Анемичная модель не имеет поведения и хранит только состояние в виде свойств.

Однако модель необязательно должна состоять только из свойств. Кроме того, она может иметь конструктор, какие-нибудь методы, поля, вообщем предствлять стандартный класс на языке C#. Модели, которые также определяют поведение, в противоположность анемичным моделям называют "толстыми" моделями (Rich Domain Model / Fat Model / Thick Model). Например, мы можем уйти от анемичной модели, модифицировав ее следующим образом:

Public class Phone { private decimal _discount = 0; public Phone(decimal discount) { this._discount = discount; } public int Id { get; set; } public string Name { get; set; } public string Company { get; set; } public decimal Price { get; set; } public decimal GetPriceWithDiscount() { return this.Price - (this.Price * this._discount); } }

Но какой бы способ описания сущности не был выбран, главное не перегружать класс модели и помнить, что его предназначение состоит прежде всего описывать данные. И модель должна описывать только одну сущность, следуя принципу единой ответственности.

В приложении ASP.NET MVC Core модели можно разделить по степени применения на несколько групп:

    Модели, объекты которых хранятся в специальных хранилищах данных (например, в базах данных, файлах xml и т.д.)

    Модели, которые используются для передачи данных представление или наоборот, для получения данных из представления. Такие модели еще называтся моделями представления

    Вспомогательные модели для промежуточных вычислений

Как правило, для хранения моделей создается в проекте отдельная папка Models . Модели представления нередко помещаются в отдельную папку, которая нередко называется ViewModels .

Проект ASP.NET MVC Core со встроенной аутентификацией по умолчанию уже содержит эти папки, и в них находятся в все необходимые модели. Однако если мы создаем проект без встроенной аутентификации, то эти папки отсутствуют. И соответственно нам надо добавить эти папки вручную. Но опять же подчеркну, что нам необязательно называть папки для хранения моделей именно Models и ViewModels. Это могут быть каталоги с любыми называниями, можно помещать модели в корень проекта, но более распространенным стилем являются названия Models и ViewModels.

Например, создадим новый проект ASP.NET Core по типу Web Application и назовем его ModelsApp . Вначале добавим в проект папку Models для хранения моделей.

И в нее поместим новый класс Company:

Public class Company { public int Id { get; set; } public string Name { get; set; } public string Country { get; set; } }

И также добавим в папку Models класс Phone

Public class Phone { public int Id { get; set; } public string Name { get; set; } public Company Manufacturer { get; set; } public decimal Price { get; set; } }

Эти модели будут описывать данные, которые мы будем использовать. Эти данные могут храниться в базе данных, но для простоты мы определим их в контроллере. Изменим контроллер HomeController следующим образом:

Using System.Collections.Generic; using System.Linq; using Microsoft.AspNetCore.Mvc; using ModelsApp.Models; // пространство имен моделей namespace ModelsApp.Controllers { public class HomeController: Controller { List companies; ListPhones; public HomeController() { Company apple = new Company { Id = 1, Name = "Apple", Country="США" }; Company microsoft = new Company { Id = 2, Name = "Microsoft", Country="США" }; Company google = new Company { Id = 3, Name = "Google", Country="США" }; companies = new List { apple, microsoft, google }; phones = new List { new Phone { Id=1, Manufacturer= apple, Name="iPhone 6S", Price=56000 }, new Phone { Id=2, Manufacturer= apple, Name="iPhone 5S", Price=41000 }, new Phone { Id=3, Manufacturer= microsoft, Name="Lumia 550", Price=9000 }, new Phone { Id=4, Manufacturer= microsoft, Name="Lumia 950", Price=40000 }, new Phone { Id=5, Manufacturer= google, Name="Nexus 5X", Price=30000 }, new Phone { Id=6, Manufacturer= google, Name="Nexus 6P", Price=50000 } }; } public IActionResult Index() { return View(phones); } } }

Список объектом модели передается в представление с помощью метода View() .

И в конце изменим представление Index.cshtml , которое будет выводить все объекты:

@using ModelsApp.Models @model IEnumerable @{ ViewData["Title"] = "Home Page"; }

@foreach (Phone p in Model) { }
@p.Name@p.Manufacturer?.Name@p.Price



Предыдущая статья: Следующая статья:

© 2015 .
О сайте | Контакты
| Карта сайта