asp.net 标识数组属性是否具有/包含重复值

uurity8g  于 2022-11-19  发布在  .NET
关注(0)|答案(3)|浏览(92)

目前我的代码,还不算太花哨。
每行都必须有会议ID值。如果会议对象中没有会议ID,则返回错误并停止所有进程(列表中每行的会议ID都相同)。
议程项目是必要的,而且不能是重复的值。如果遗漏或重复,则会传回错误。
如果缺少Legistar ID,则议程项目的值将分配给缺少的Legistar ID。
议程项目和/或Legistar ID都不能包含重复值这些属性每个值都必须唯一否则,将停止,并返回错误
我尝试传递并验证的列表如下所示:

AgendaItem  LegistarID  Title
1   74490   Public Comment. (October 31 2022)
2   74491   Welcome Affirmative Action Commission Appointment. <-- Agenda Item 2
2   73403   Nomination Open Update.                            <-- Agenda Item 2
4   74490   Communication Strategy Update.                     <-- Legistar Id same as row 1

如何传递指定此类特定情况的消息,以便客户端应用程序接收并提醒用户?
这是我的ImportData例程的当前版本,这里没有任何内容

public ActionResult ImportData(List<MeetingAgendaXref_WIP> meeting) // see comment above procedure name
{

    bool status = false;
    string message = "";

    try
    {
        if (ModelState.IsValid)
        {
            var errors = new List<string>();
            var rowCounter = 1;

            using (ClerkEntities db = new ClerkEntities())
            {
                foreach (var i in meeting)
                {

                    if (i.MeetingID == 0)
                    {

                        message = string.Format("No Meeting ID. Please make sure that the Cross Reference meets the required criteria for each row before clicking the ""Upload"" button.");
                        // log error to list
                        errors.Add($"Row {rowCounter}: No Meeting ID. Please make sure that the Cross Reference meets the required criteria for each row before clicking the ""Upload"" button.");
                        return new JsonResult { Data = new { status = status, message = message } };

                    }

                    if (i.AgendaItem == 0)
                    {
                        message = string.Format("No Agenda Item. Please make sure that the Cross Reference file meets the required criteria for each row before clicking the ""Upload"" button.");
                        // log error to list
                        errors.Add($"{rowCounter}:No Agenda Item. Please make sure that the Cross Reference file meets the required criteria for each row before clicking the ""Upload"" button.");
                        return new JsonResult { Data = new { status = status, message = message } };
                    }

                    // if Legistar ID, 
                    if (i.LegistarID == 0)
                    {
                        // and Agenda Item are not present, return error message, log error message
                        if (i.AgendaItem == 0)
                        {
                            message = string.Format("Agenda Item, and Legistar Id are missing. Please make sure that the Cross Reference file meets the required criteria for each row before clicking the ""Upload"" button.");
                            // log error to list
                            errors.Add("Agenda Item, and Legistar Id are missing. Please make sure that the Cross Reference file meets the required criteria for each row before clicking the ""Upload"" button.");
                            return new JsonResult { Data = new { status = status, message = message } };
                        }
                        // otherwise, if legistar id, is empty, but agenda item is not, then assign Agenda Item to Legistar Id.
                        else
                        {
                            i.LegistarID = i.AgendaItem;
                        }
                    }

                    var compositeKey = db.MeetingAgendaXref_WIP.Find(i.MeetingID, i.AgendaItem);

                    if (compositeKey == null)
                    {
                        // Add new
                        db.MeetingAgendaXref_WIP.Add(i);

                    }
                    else
                    {
                        // Update previously saved values (same or new)
                        db.Entry(compositeKey).CurrentValues.SetValues(i);
                        db.Entry(compositeKey).State = EntityState.Modified;
                    }
                    rowCounter++;
                }
                
                // If there are errors do not save and return error message
                if (errors.Count > 0)
                {
                    return new JsonResult { Data = new { status = status, message = string.Join("\n", errors) } };
                }
                else
                {
                    db.SaveChanges();
                    message = string.Format(@"Your Cross Reference file has been uploaded successfuly!");
                    status = true;
                    return new JsonResult { Data = new { status = status, message = message } };
                }
            }
        }
        else
        {
            message = string.Format(@"Please make sure that the Cross Reference file meets the required criteria for each row before clicking the ""Upload"" button.");
            return new JsonResult {Data = new {status = status, message = message}};
        }
    }
    catch (System.ArgumentException ex)
    {
        status = false;
        ExceptionLogging.WriteLogError(ex.ToString());
    }
    return new JsonResult {Data = new {status = status, message = message}};
}
jgwigjjp

jgwigjjp1#

所以基本上,我们需要对这些字段进行3次验证(MeetingIDAgendaItemLegistarID)。因为我不知道asp.net的语法。我在这里用纯JavaScript格式演示这个解决方案,只是为了给予你知道它是如何工作的。你可以根据具体的语言来做相应的工作。
我只是将上面的表数据转换为一个对象数组,其中每个对象将定义一行数据。

[{
  MeetingID: 102,
  AgendaItem: 1,
  LegistarID: 74490,
  Title: 'Public Comment. (October 31 2022)'
}, {
    MeetingID: 102,
  AgendaItem: 2,
  LegistarID: 74491,
  Title: 'Welcome Affirmative Action Commission Appointment.'
}, {
    MeetingID: 102,
  AgendaItem: 2,
  LegistarID: 73403,
  Title: 'Nomination Open Update.'
}, {
    MeetingID: 102,
  AgendaItem: 4,
  LegistarID: 74490,
  Title: 'Communication Strategy Update.'
}]

实时演示(所有描述性注解都已添加到以下代码片段中)

const arr = [{
  MeetingID: 102,
  AgendaItem: 1,
  LegistarID: 74490,
  Title: 'Public Comment. (October 31 2022)'
}, {
  MeetingID: 102,
  AgendaItem: 2,
  LegistarID: 74491,
  Title: 'Welcome Affirmative Action Commission Appointment.'
}, {
  MeetingID: 102,
  AgendaItem: 2,
  LegistarID: 73403,
  Title: 'Nomination Open Update.'
}, {
  MeetingID: 102,
  AgendaItem: 4,
  LegistarID: 74490,
  Title: 'Communication Strategy Update.'
}];

// Condition to check if each object in an array contains the MeetingID.
const meetingIdCondition = arr.every(({ MeetingID }) => MeetingID);

const agendaItemArr = arr.map(({ AgendaItem }) => AgendaItem);
const checkForDuplicateAgendaItem = agendaItemArr.filter((item, index) => agendaItemArr.indexOf(item) !== index);

// Condition to check if each object in an array contains the AgendaItem and should be unique.
const agendaItemCondition = arr.every(({ AgendaItem }) => AgendaItem) && !checkForDuplicateAgendaItem.length;

const legistarIdArr = arr.map(obj => {
    if (!obj.LegistarID) {
    obj.LegistarID = obj.AgendaItem;
  }
  return obj.LegistarID;
});
const checkForDuplicateLegistarId = legistarIdArr.filter((item, index) => legistarIdArr.indexOf(item) !== index);

// Condition to check if each LegistarId should be unique.
const legistarIdCondition = !checkForDuplicateLegistarId.length;

// Here is the final code to check if any of the validation fails.
if (!meetingIdCondition || !agendaItemCondition || !legistarIdCondition) {
    console.log('validation failed');
} else {
    console.log('all validation passed');
}
qnzebej0

qnzebej02#

“检查数组是否包含具有某些()的重复项
要检查数组是否包含重复项:
1.使用Array.some()方法迭代数组。
1.检查当前值第一次出现的索引是否不等于其最后一次出现的索引。
1.如果满足条件,则数组包含重复项。”

const arr1 = ['a', 'a'];
    const arr2 = ['a', 'b'];    
    function containsDuplicates(array) {
      const result = array.some(element => {
        if (array.indexOf(element) !== array.lastIndexOf(element)) {
          return true;
        }
        return false;
      });
    return result;
    }
    console.log(containsDuplicates(arr1)); // 👉️ true
    console.log(containsDuplicates(arr2)); // 👉️ false

https://bobbyhadz.com/blog/javascript-check-if-array-contains-duplicates#check-if-an-array-contains-duplicates-with-some

hrysbysz

hrysbysz3#

对我来说,依靠客户端发送有效数据听起来很可怕,因为你可能无法阻止数据从任意来源到达。因此,每个后端都应该验证传入的数据,如果它没有隐藏在与其客户端的专用网络中。
您可以使用LINQ的GroupBy检查属性中是否有非唯一的条目,如下所示:

// for demo purpose define a "Meeting" record and create a few meetings with random numbers
public record Meeting(int MeetingId, int AgendaItem, int LegistarId, string Title) { }

var rnd = new Random();  
var meetings = Enumerable.Range(1, 100)
    .Select(n => new Meeting(1, rnd.Next(200), 1000 + rnd.Next(200), $"Meeting #{n}"));

// check for doubles among the "AgendaItem" values
var agendaDoubles = meetings.GroupBy(m => m.AgendaItem).Where(m => m.Count() > 1);

// check for doubles among the "LegistarId" values
var legistarDoubles = meetings.GroupBy(m => m.LegistarId).Where(m => m.Count() > 1);

对于每个非唯一值,GroupBy将给予如下结构:

其中Key是不唯一的AgendaItem,并且Grouping包含具有相应的AgendaItem值的所有记录。
现在,您可以创建一条消息,列出所有非唯一的AgendaItem,如下所示:

var agendaDoublesAsText = string.Join(',', agendaDoubles.Select(m => m.Key));

您可能仍然需要处理这样一个事实,即用于替换LegistarId值“0”的AgendaItem可能已经存在于非零LegistarId中,但这可以通过在双精度检查之前替换这些值来轻松实现。
代码注解:内部if in

// if Legistar ID,
if (i.LegistarID == 0)
{
   // and Agenda Item are not present, return error message, log error message
   if (i.AgendaItem == 0)
...

已过时,因为它已在前面的if语句中被选中,并且永远不会为真。

相关问题